What is a type assertion in TypeScript?

Why Interviewers Ask This

This question tests conceptual clarity. Interviewers want to hear a precise, confident definition before moving to more complex TypeScript topics. It also reveals how well you can explain technical ideas to non-experts.

Answer

A type assertion is a way to tell the TypeScript compiler "I know the type of this value better than you do." It does NOT perform any runtime type conversion — it is purely a compile-time instruction. Two syntaxes: value as Type (preferred, works in JSX) and <Type>value (older syntax, does not work in TSX files). Example: const input = document.getElementById("name") as HTMLInputElement; — TypeScript knows getElementById returns HTMLElement | null, but you assert it is specifically an HTMLInputElement to access .value. Non-null assertion: value! asserts that a value is not null or undefined. Use type assertions sparingly — if you are wrong about the type, you will get runtime errors with no compile-time warning. Prefer type guards and proper typing over assertions. Double assertion: if TypeScript rejects a direct assertion, you can bridge through unknown: value as unknown as TargetType — a strong signal that something suspicious is happening.

Pro Tip

This topic has TypeScript-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.