← Lessons

quiz vs the machine

Silver1040

Frontend

Type Inference Basics

How TypeScript figures out types so you do not have to annotate everything.

4 min read · intro · beat Silver to climb

What inference is

TypeScript reads your code and assigns a type to a value even when you write no annotation. This keeps code light while still catching mistakes.

Where it happens

  • Variable initializers infer from the right side. A value set to a number gets the number type.
  • Return types infer from what a function actually returns.
  • Default parameters infer from the default value you supply.

Let versus const

The widening rules differ. A const holding a string literal keeps the literal type, like the exact word red. A let holding the same value widens to the broader string type, because a let can be reassigned later.

Best common type

When an array mixes values, TypeScript picks the best common type that fits every element. An array of a few numbers becomes an array of number. If no single type fits, it falls back to a union of the members.

When to annotate

Let inference do the work for locals. Add explicit annotations at function boundaries and exported values, where a clear contract helps readers and prevents accidental widening from leaking across your codebase.

Key idea

Inference assigns types from the values you write; annotate the boundaries and let the body infer itself.

Check yourself

Answer to earn rating on the learn ladder.

1. What type does a const holding the string red infer?

2. Where is adding an explicit annotation most valuable?