Q17: What are Type Assertions (`as T`) and how do they differ from Type Casting?

Difficulty:EasyTopic:Type Assertions

Type Assertions instruct the compiler to treat a value as a specific type using the syntax val as T or <T>val.

Type assertions do not perform runtime conversion (casting). They are purely compile-time directives removed during compilation. To convert runtime types (e.g., string to number), you must call JavaScript conversion functions like Number(str).

Key Takeaways
  • Type assertions do not change runtime JavaScript data structures.
  • Use as unknown as TargetType for double assertions when types do not overlap.