Codectionary / Developer documentation / TypeScript

Type Inference

TypeScript can automatically determine a value's type from its initializer, without an explicit annotation - this is type inference. It reduces boilerplate significantly while still providing full type safety. Understanding what TypeScript infers (and when it needs help) is key to writing idiomatic, uncluttered TypeScript.

Syntax

const value = expression; // type is inferred automatically

Examples

Basic Inference

TypeScript infers types from initial values without needing annotations.

let count = 10;        // inferred as: number
let name = "Alice";     // inferred as: string
let items = [1, 2, 3];  // inferred as: number[]

// count = "ten"; // Error - TypeScript remembers count is a number, even without an explicit annotation

Contextual Typing and Return Type Inference

TypeScript also infers types based on how a value will be used, and infers function return types.

window.addEventListener("click", (event) => {
  console.log(event.button); // "event" is inferred as MouseEvent from context - full autocomplete works
});

function add(a: number, b: number) {
  return a + b; // return type inferred as: number, no annotation needed
}

Best practices

  • Let TypeScript infer types for local variables initialized with an obvious value - explicit annotations there are usually redundant noise
  • Still explicitly annotate function parameters, since TypeScript cannot infer those from usage the way it can return types
  • Explicitly annotate a variable's type when it starts as one value but needs to later hold a broader type, like let result: string | null = null
  • Use your editor's "hover to see inferred type" feature regularly - it is the fastest way to build intuition for how TypeScript reasons about your code

At a glance

Purpose
Static types for JavaScript
File extension
.ts ยท .tsx
Runs in
Compiled to JavaScript
Usually used with
JavaScript and its ecosystem

Specifications & further reading

Related TypeScript documentation