What is type inference in TypeScript?

Why Interviewers Ask This

Interviewers use this question to quickly assess whether a candidate has the foundational knowledge required for TypeScript development. It reveals whether you understand the building blocks that more complex concepts rely on.

Answer

Type inference is TypeScript's ability to automatically determine the type of a variable or expression without explicit annotation. When you initialize a variable at declaration, TypeScript infers its type from the assigned value: let count = 5 → TypeScript infers number. let message = "hello" → inferred as string. For functions, the return type is inferred from the return statement: function add(a: number, b: number) { return a + b; } — return type inferred as number. TypeScript also infers array element types from initial values. Inference works in most contexts — contextual typing even infers types from the surrounding context, like the type of a callback's parameters based on where it is used. Best practice: rely on inference for local variables, but always annotate function parameters and public API return types for clarity and documentation.

Pro Tip

This topic has TypeScript-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.