๐ŸŽ“ A1Learner
๐Ÿ”

TypeScript Type Inference

Type inference means the compiler takes the type of a variable from its first value. No annotation is written.

An inferred number

No annotation is written here. The compiler reads the type from the value 42.

let score = 42;
console.log(typeof score);

The inferred type still holds

A string cannot replace the number. The inferred type blocks the change.

let score = 42;
score = "high";
console.log(score);

Runtime types are JavaScript types

Two more inferred variables report their runtime types below.

let label = "done";
let ready = false;
console.log(typeof label);
console.log(typeof ready);

Example

let item = "pen";
let price = 4;
let inStock = true;
console.log(item);
console.log(price);
console.log(inStock);

Key points

  • Inference takes the type from the first value.
  • An inferred variable still refuses values of other types.
  • The typeof operator reports the runtime type of a value.
  • Types are erased when JavaScript is emitted.
  • typeof reports a JavaScript type at runtime.

In this example, three variables start with no annotations. The compiler infers string for item and number for price. It infers boolean for inStock. The log lines print the three values in order.

Note

An annotation and inference can give a variable the same type.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท TypeScript Playground

Exercise

What type does the compiler infer for a variable that starts with the value 5?