Question presented to candidate: "A lot of TypeScript code has hardly any type annotations, yet it is fully typed. How does type inference work, where does it come from, and when do you still need to write types yourself?"
What a strong answer should cover:
- Inference from initializers, array elements (best common type as a union), object literals and return statements; the result is fixed, not dynamic
- Contextual typing: callback parameters and functions assigned to a typed variable get their types from context
- Literal widening:
constkeeps"dark",letand object properties widen tostring;as constand annotations prevent it - Limits: parameters are not inferred from call sites (
TS7006undernoImplicitAny), empty arrays evolve, mixed arrays do not get a supertype - Control flow analysis narrows a variable after assignments and checks, separate from its declared type
- Where to annotate: parameters, public return types, empty collections, object literals that must match a shape
Code / implementation expected: Optional β a few declarations with the inferred type stated, ideally proven with a compile-time check.