Skip to content
BENIBIX Learn

Type Inference

Also known as Inferred Type, Type Deduction

The language works out each value's type. You do not have to write it.

Think of it like

Think of it like a box shaped for shoes. You can guess what is in it.

Example

Emma writes let count = 5 and later sets count to the word five. TypeScript stops her, though she never wrote number anywhere.

Why it matters

It keeps typed code short. You write types where they help a reader, and let the language fill in the rest.

Definition

Type inference is when the language works out a value's type without you writing it. If you write let count = 5, TypeScript knows count is a number. From then on it holds you to that, so putting text in count is an error. You get the safety of types with less typing. Go, Rust, Kotlin, Swift and TypeScript all do it.

Example code

typescript
let count = 5;
count = "five";
// Type 'string' is not assignable to type 'number'.
TypeScript guessed number from the 5, and refuses the text.

Common mistake

Thinking an inferred type is a loose type. Once inferred, it is checked just as strictly as one you wrote.

Key takeaways

  1. 1
    Worked out for you. From the value you give.
  2. 2
    Still strict. Checked like a written type.
  3. 3
    Less to type. Same safety.

Compare