What is type inference in TypeScript?
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.