TypeScript ยท Chapter 6 of 44

TypeScript Type Inference

TypeScript is smart enough to figure out the type of a variable automatically based on the value you assign to it, even without an explicit annotation. This is called type inference.

Because of inference, you often don't need to write types everywhere. TypeScript infers types for variables, function return values, and more, while still catching type errors if you later try to misuse the variable.

Syntax
let city = "Paris"; // inferred as string

Inference for variables

When you write `let city = "Paris";`, TypeScript infers that city is a string, even though you never wrote `: string`. It will still flag an error if you later assign a number to city.

Inference for return values

TypeScript can also infer a function's return type from its body, so writing the return type explicitly is often optional but can still be useful for documentation.

Example 1 (typescript)
let city = "Paris";
console.log(typeof city);
Output
string

TypeScript infers that city is a string from its initial value.

Example 2 (typescript)
function double(n: number) {
  return n * 2;
}
const result = double(4);
console.log(result);
Output
8

TypeScript infers that double returns a number, without an explicit return type annotation.

Key points

  • Type inference lets TypeScript detect types without explicit annotations.
  • Inferred types are just as strict as annotated types.
  • Function return types can also be inferred from the function body.
  • Explicit annotations are still useful for clarity in public APIs.
๐Ÿ’ก Note: Rely on inference for local variables, but consider explicit types for function parameters and public function signatures.

๐Ÿ“ Quick Quiz

1. What is type inference?

2. In `let x = 5;`, what type does TypeScript infer for x?

3. Can TypeScript infer function return types?