What is type assertion in TypeScript
· Category: TypeScript
Short answer
A type assertion tells the TypeScript compiler to treat a value as a specific type. Use the as keyword or angle-bracket syntax.
Steps
- Assert with
as:const canvas = document.getElementById('canvas') as HTMLCanvasElement; - Use angle brackets in non-TSX files:
const input = <HTMLInputElement>document.getElementById('name'); - Chain assertions cautiously:
value as unknown as TargetTypefor forced conversions. - Prefer type guards over assertions when runtime validation is possible.
- Avoid asserting away legitimate type errors.
Tips
- Type assertions do not perform runtime conversion; they are compile-time only.
- Use
satisfies(TypeScript 4.9+) when you want to check a type without widening.
Common issues
- Overusing
as anyundermines the type system and hides real bugs. - Assertions to a more specific type than the runtime value can lead to runtime crashes.