What is a type assertion?
Answer
TypeScript adds a static type system to JavaScript. Explain the compile-time guarantee, distinguish it from runtime validation, and use narrow, readable types instead of escaping to any.
For What is a type assertion?, start with the rule or behaviour, then anchor it in a small realistic example. Distinguish the default approach from the exceptions and name the observable outcome: correctness, maintainability, accessibility, performance, or security.
Example
ts
function formatId(id: string | number) {
return typeof id === "string" ? id.trim() : id.toString()
}The typeof check narrows the union, so each branch gets the operations valid for that type.
How to structure your answer
- Define the concept in one or two sentences.
- Explain when you would use it and when you would choose an alternative.
- Walk through a small example, including an edge case.
- Close with how you would test or measure the result.
Common mistakes
- Repeating a definition without connecting it to real code.
- Treating an optimization or abstraction as a default rather than a trade-off.
- Omitting lifecycle, error, cleanup, accessibility, or testing considerations when they apply.
Follow-up prompts
- What failure mode would you expect if this were implemented incorrectly?
- How would you test this behaviour?
- What changes when the feature must scale to a larger application or team?
Interview tip
For this medium-level question, narrate your assumptions before coding. Interviewers can assess reasoning from a clear, bounded example much better than from a list of APIs.