tezvyn:

Explain what TypeScript's type inference is and show an inferred variable declaration

AI-drafted, machine-checkedSource: typescriptlang.orgbeginner

This tests whether you understand TypeScript deduces types without annotations. A strong answer defines inference as deriving types from values and gives an example like let x = 3 inferring number. A red flag is claiming explicit types are required.

WHAT THIS TESTS: This question checks whether you understand that TypeScript can automatically deduce static types without explicit annotations, and whether you know the practical places where inference occurs. At the senior level, interviewers also listen for awareness of inference limits, such as best common type and contextual typing.

A GOOD ANSWER COVERS: First, define type inference as the compiler analyzing the right-hand side of an assignment to determine the left-hand side's type. Second, give a minimal code example such as declaring let x = 3 and noting that TypeScript infers the type number. Third, mention that inference extends beyond simple variables to function return types, parameter default values, and object properties. Fourth, briefly note the nuance of best common type, where an array like let arr = [0, 1, null] becomes (number | null)[], and contextual typing, where the expected type of a location influences the expression's type, such as a callback parameter in window.onmousedown.

COMMON WRONG ANSWERS: A major red flag is claiming that TypeScript always requires explicit type annotations or that omitting an annotation defaults to any. Another mistake is confusing type inference with type coercion or runtime behavior; inference is a compile-time static analysis feature only. Candidates also stumble by providing overly complex generics when a simple literal example is requested.

LIKELY FOLLOW-UPS: The interviewer may ask how inference differs from explicit typing in terms of readability and maintainability. They might probe edge cases, such as why let zoo = [new Rhino(), new Elephant()] infers a union instead of a common base class like Animal, or how strictNullChecks affects inferred types. You may also be asked to compare inference in function expressions versus declarations.

ONE CONCRETE EXAMPLE: A clean snippet is let message = "hello"; Here TypeScript infers string without an annotation. If you later try message = 42; the compiler emits a type error because the inferred type is fixed. For a function, function add(a = 1, b = 2) { return a + b; } infers a and b as number and the return type as number. If the function body changed to return a > b, the return type would automatically infer boolean instead.

Read the original → typescriptlang.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.