ProgrammingFrontend Developer / Fullstack Developer

How does the type inference system work in TypeScript? What are the levels of type inference and what mistakes can be made by relying on the compiler's 'intelligence'?

Pass interviews with Hintsage AI assistant

Answer

TypeScript has a powerful type inference system. In most cases, the types of variables, parameters, and return values are automatically calculated based on context. There are several levels of type inference:

  • Simple inference: when declaring variables without an explicit type
  • Contextual inference: when the type of an expression is determined from the context (e.g., event handler)
  • Best common type: for arrays with elements of different types — the most general type is sought

Examples:

let a = 2; // number let b = [1, "a"]; // (number | string)[] window.addEventListener('click', e => { // e: MouseEvent });

Limitation: if the compiler cannot unambiguously infer the type — it will choose the broadest type (usually any), which negates the benefits of typing.

Trick question

Is the function argument typed if not explicitly specified, but the function is later used with a typed value?

Wrong answer: Yes, TypeScript will always automatically "guess" the argument type.

Correct answer: No. Only if the function context contains type information will the argument be typed. Otherwise, it will be any or another basic type, leading to errors. It's always a good practice to explicitly type input data.

Example:

function f(x) { return x.toFixed(2); // Error: x is of type any }

Examples of real errors due to ignorance of the subtlety of this topic


Story

In a project, the return type of a custom React hook was not explicitly specified, and TypeScript did not see that the type could be undefined. As a result, calling a method on an object without a check led to runtime errors.


Story

When creating an array of mixed-type values, the final type was automatically inferred as an any[] array because a type was not explicitly specified, which led to the loss of all typing benefits in the subsequent code.


Story

The validation of service input parameters was not typed and relied on TypeScript's "guessing". After refactoring the codebase, automatic inference resulted in too broad a type, and data type errors made it to production.