Type assertions in TypeScript are a way to tell the compiler explicitly that you know the type of a variable better than it does. They are used when you have more information about the type of a value than TypeScript’s type checker is able to infer. Type assertions do not perform any runtime checks or conversions; they simply inform the compiler of the assumed type.
Syntax
Type assertions can be done in two ways:
Angle-bracket syntax:
let someValue: any = "this is a string";
let strLength: number = (someValue).length;
as
syntax:
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;
Examples
Example 1: Narrowing a type
Consider a scenario where you know a variable is of a more specific type than what TypeScript infers:
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;
console.log(strLength); // Outputs: 16
Here, TypeScript would not know the exact type of someValue
, but you, as the developer, know it’s a string. The type assertion someValue as string
informs the compiler about this knowledge.
Example 2: Working with DOM elements
When working with the DOM, TypeScript often cannot infer the exact type of an element, especially when using methods like document.getElementById
.
let inputElement = document.getElementById("input") as HTMLInputElement;
inputElement.value = "Hello, world!";
Without the type assertion, document.getElementById
would return HTMLElement | null
, and TypeScript would not know about the value
property of HTMLInputElement
.
Type Assertions vs Type Casting
Type assertions in TypeScript do not perform any runtime checks or type conversions. They purely tell the compiler to treat a value as a specific type, which is different from type casting in other languages that convert the type at runtime.
For example, in TypeScript:
let someValue: any = "this is a string";
let strLength: number = (someValue).length; // Type assertion
In contrast, in languages like C# or Java, type casting may involve actual runtime type conversion.
Type Assertions with Union Types
When dealing with union types, type assertions can help specify the exact type you are working with.
function getLength(value: string | number): number {
if ((value as string).length !== undefined) {
return (value as string).length;
} else {
return value.toString().length;
}
}
console.log(getLength("Hello")); // Outputs: 5
console.log(getLength(12345)); // Outputs: 5