TypeScript Developer interview question · Most asked
What are type assertions (`as`) and the non-null assertion (`!`), and why should you use them sparingly?
Summary
value as T tells the compiler to treat a value as T, and value! asserts it isn't null/undefined. Neither does anything at runtime; if you're wrong, you get runtime errors the compiler could have caught.
Longer Answer
Prefer narrowing, type guards or validation. Assertions are acceptable when you genuinely know more than the compiler (e.g., DOM elements guaranteed by the template), but as unknown as T double-casts are a code smell. ESLint rules can restrict them.
Key Points
- Compile-time only, no runtime effect
- Prefer narrowing/validation
!hides possible undefined- Avoid
as unknown as T
More most-asked TypeScript Developer questions
- Explain `any`, `unknown` and `never`.
- What are the differences between `interface` and `type` aliases?
- What is structural typing in TypeScript?
- What is type narrowing and what techniques does TypeScript support?
- What are discriminated unions and why are they powerful?
- What are generics and how do constraints work?
- Which built-in utility types do you use most, and what do they do?
- What is TypeScript and what problems does it solve?