Q23. What is the difference between a type assertion and a conversion?
A type assertion tells the compiler to treat a value as a specified type; it does not transform or validate the value. A conversion changes a runtime value, and validation checks that a value satisfies a runtime contract. Use assertions only when supported by evidence.
JSON.parse(text) as User does not prove the JSON contains User's fields. Validate before trusting external data.
Note
Interview approach: define the concept, explain why it matters, then mention one trade-off or limitation.
TypeScript concept
// Illustrative TypeScript contract
type Identifier = string;
const id: Identifier = "item-1";💡 The example demonstrates the compile-time contract discussed in this question.
Key Takeaways
- Explain the concept in your own words.
- Know the practical trade-off and its limits.
- Use a small example to demonstrate the idea.
Knowledge Check
What does `value as number` do at runtime?