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

  1. Assert with as: const canvas = document.getElementById('canvas') as HTMLCanvasElement;
  2. Use angle brackets in non-TSX files: const input = <HTMLInputElement>document.getElementById('name');
  3. Chain assertions cautiously: value as unknown as TargetType for forced conversions.
  4. Prefer type guards over assertions when runtime validation is possible.
  5. 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 any undermines the type system and hides real bugs.
  • Assertions to a more specific type than the runtime value can lead to runtime crashes.