liveBook · Manning

Type inference

As explained in Secrets of the JavaScript Ninja, Third Edition

The compile-time determination of types from surrounding declarations, expressions, or values without requiring explicit annotations.

Type inference lets TypeScript determine types from nearby declarations, expressions, and values, reducing the need for annotations. For example, an assigned value can determine a variable’s type, and a callback’s context can determine its parameter type. section 2.1.2

Inference is useful, but it depends on what TypeScript can see:

  • A default parameter gives TypeScript a basis for inferring its type; a parameter without a default generally needs an annotation. section 5.5.1 section 5.5.2
  • If an untyped function parameter has no contextual type, TypeScript falls back to any. With noImplicitAny enabled, that implicit any triggers an error. section 2.1.2
  • For a function’s return type, TypeScript considers the possible returned values and infers a type that accommodates them. An explicit return annotation can help catch missing cases. section 5.5.2
numberSign.ts:1:35 - error TS2366: Function lacks ending return statement and return type does not include 'undefined'.
 
1 const numberSign = (num: number): "positive" | "negative" => {

A declared return type exposes a missing case: the function omits a return for zero, which the type checker reports. section 5.5.2

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Explains inference from assigned values and context, default parameters, and function returns, including when annotations improve checking.
Examples
Uses inferred variable and callback types, default parameters, and a capitalization function with an inferred return type.
What you can do after
Apply TypeScript inference to omit redundant annotations and add parameter or return types where needed for reliable checking.
How it connects
Connects type inference to TypeScript type annotations, contextual typing, the any type, and union types.

Also explained in

Compare how 19 books explain type inference →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.