Type Assertion in TypeScript is a way to hint to the compiler that you know more about a particular value’s type than the type inference system does. Type assertion allows you to explicitly specify the type of a value, and it is a way of telling the TypeScript compiler that you are certain about the type of a variable or expression.
There are two ways to perform type assertion in TypeScript:
1. Using angle-bracket syntax:
let value: any = "This is a string";
let strLength: number = (<string>value).length;
2. Using the ‘as‘ keyword:
let value: any = "This is a string";
let strLength: number = (value as string).length;
In both cases, you are asserting that the value has the specified type (in this case, ‘string‘). Note that this operation does not perform any runtime type checks or conversions; it only serves as a hint to the TypeScript compiler.
Here’s an example with a shape interface and a function to calculate its area with type assertion:
interface Circle {
kind: "circle";
radius: number;
}
interface Square {
kind: "square";
sideLength: number;
}
type Shape = Circle | Square;
function getArea(shape: Shape): number {
if (shape.kind === "circle") {
return Math.PI * (shape as Circle).radius ** 2;
} else {
return (shape as Square).sideLength ** 2;
}
}
In this example, we use type assertion to inform the TypeScript compiler that ‘shape‘ is a ‘Circle‘ or ‘Square‘ based on its ‘kind‘ property.
It’s important to note that type assertion should be used with caution, as it can lead to runtime errors if used improperly or excessively. Use type assertion only when you are sure about the value’s type, and it’s not feasible for the TypeScript compiler to infer it.