- TypeScript Tutorial
- TypeScript Home
- TypeScript Introduction
- TypeScript Setup
- TypeScript First Program
- TypeScript vs JavaScript
- TypeScript Data Types
- TypeScript Type Inference
- TypeScript Type Annotations
- TypeScript Interfaces
- TypeScript Enums
- TypeScript Type Aliases
- TypeScript Type Assertions
- TypeScript Variables
- TypeScript Functions
- TypeScript Functions
- TypeScript Optional Parameters
- TypeScript Default Parameters
- TypeScript Rest Parameters
- TypeScript Arrow Functions
- Classes and Objects
- Introduction to Classes
- Properties and Methods
- Access Modifiers
- Static Members
- Inheritance
- Abstract Classes
- Interfaces vs Classes
- Advanced Types
- TypeScript Union Types
- TypeScript Intersection Types
- TypeScript Literal Types
- TypeScript Nullable Types
- TypeScript Type Guards
- TypeScript Discriminated Unions
- TypeScript Index Signatures
- TypeScript Generics
- Introduction to Generics
- TypeScript Generic Functions
- TypeScript Generic Classes
- TypeScript Generic Constraints
- TypeScript Modules
- Introduction to Modules
- TypeScript Import and Export
- TypeScript Default Exports
- TypeScript Namespace
- Decorators
- Introduction to Decorators
- TypeScript Class Decorators
- TypeScript Method Decorators
- TypeScript Property Decorators
- TypeScript Parameter Decorators
- Configuration
- TypeScript tsconfig.json File
- TypeScript Compiler Options
- TypeScript Strict Mode
- TypeScript Watch Mode
TypeScript Type Assertions
Type assertions in TypeScript allow you to tell the compiler to treat a value as a specific type. They don't perform type checking or data conversion but provide a way to override the inferred type for better control.
Why Use Type Assertions?
- Helps when TypeScript cannot infer the correct type.
- Useful when working with dynamic data, such as data from APIs.
- Enables access to specific properties or methods of a type.
Syntax for Type Assertions
There are two ways to write type assertions in TypeScript:
Angle-bracket syntax (<Type>
):
let value: any = "Hello, TypeScript";
let length = (<string>value).length;
console.log(length); // Output: 16
as
syntax:
let value: any = "Hello, TypeScript";
let length = (value as string).length;
console.log(length); // Output: 16
Both approaches achieve the same result, but the as
syntax is preferred in JSX to avoid conflicts.
Type Assertions for DOM Manipulation
When working with the DOM, TypeScript may not know the exact type of an element. Type assertions help you access specific properties.
let inputElement = document.getElementById("username") as HTMLInputElement;
inputElement.value = "John Doe";
console.log(inputElement.value); // Output: John Doe
Type Assertions with Unknown and Any
Type assertions are especially useful with unknown
and any
types.
Example with unknown
:
let someValue: unknown = "TypeScript";
let length = (someValue as string).length;
console.log(length); // Output: 10
Example with any
:
let someValue: any = 12345;
let stringValue = someValue as string;
console.log(stringValue); // No error but runtime result is 12345
Type Assertions with Custom Types
Type assertions allow you to narrow down to a specific custom type.
type User = { name: string; age: number };
let data: any = { name: "Alice", age: 25 };
let user = data as User;
console.log(user.name, user.age); // Output: Alice 25
Non-Null Assertions
The non-null assertion operator (!
) tells TypeScript that a value is not null
or undefined
.
let input = document.querySelector("#inputField")! as HTMLInputElement;
input.value = "Not Null";
console.log(input.value); // Output: Not Null
Type Assertions with Union Types
You can use type assertions to narrow union types to a specific type.
function getLength(value: string | number) {
if ((value as string).length !== undefined) {
return (value as string).length;
}
return value.toString().length;
}
console.log(getLength("Hello")); // Output: 5
console.log(getLength(12345)); // Output: 5
Type Assertions vs Type Casting
- Type assertions don't change the data at runtime; they only tell the TypeScript compiler to treat the value differently.
- Type casting in other languages, like C++, may convert values at runtime, which TypeScript does not do.
Summary
Type assertions in TypeScript allow you to tell the compiler what type a value should be treated as. They are useful for scenarios where TypeScript cannot infer the correct type, such as DOM manipulation, working with any
or unknown
types, and complex custom types. Use them responsibly as they override TypeScript's type safety.