What does TypeScript add to JavaScript, and what happens to its types at runtime?
Quick interview answer
TypeScript adds static type checking to JavaScript. It can catch many mistakes while you write or build code, such as passing a string where a number is expected. TypeScript code is transformed into JavaScript, and the type annotations are erased. That means TypeScript types do not validate data at runtime.
Detailed explanation
The compiler checks types before the program runs. A successful check does not guarantee that external data is safe or that the program has no bugs. Use runtime validation at boundaries such as API responses.
Code example
function double(value: number): number {
return value * 2;
}
console.log(double(4)); // 8The number annotations help TypeScript check calls but are absent from emitted JavaScript.
Real-world example
An API client uses types for editor help and a runtime schema to check an untrusted JSON response.
Common interview mistakes
Claiming TypeScript types exist as runtime validators.
Assuming a successful type check guarantees correct program behavior.
Follow-up questions
- 1
Can TypeScript prevent every runtime error?
- 2
How would you validate data received from an API?