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

← All TypeScript Developer questions