Type Assertions allow you to tell TypeScript to treat a variable as a specific type, overriding its inferred type. It’s similar to type casting in other languages, but without any special checking or restructuring.
Example 1: Basic Type Assertion
let someValue: any = "this is a string";
let strLength: number = (<string>someValue).length;- Here,
someValueis of typeany, but we know it’s a string, so we assert it as astringusing<string>someValue. - Then we access the
lengthproperty, which TypeScript knows is valid for a string.
Example 2: Using as Syntax (alternative to <string>)
let strLength: number = (someValue as string).length;- The
assyntax is the alternative to the<type>syntax and is preferred in JSX/TSX files (for React).
Key Points:
- Type assertions are used to tell TypeScript the specific type of a variable when TypeScript cannot infer it automatically.
<type>valueandvalue as typeare two ways to write type assertions.- Type assertions do not perform any runtime checks; they just tell TypeScript to treat the value as a specified type.