Lesson 3 +10 XP

Type Annotations & Inference

Type Annotations & Type Inference

TypeScript allows you to explicitly state types using type annotations or let the compiler guess them using type inference.

Explicit Type Annotations

Syntax: let identifier: type = value;

let age: number = 30;
let name: string = "Bob";
let isStudent: boolean = true;

Type Inference

If you do not specify a type, TypeScript infers it based on the initial value:

let score = 100; // Inferred as 'number'
score = "one hundred"; // Compile error: Type 'string' is not assignable to type 'number'.

When to Use Explicit Annotations vs Inference

  • Inference: Use for simple local variable initializations to keep code clean.
  • Annotations: Use for function parameters, function return types, or when a variable is declared before assignment.
function add(a: number, b: number): number {
  return a + b;
}

TL;DR

  • Annotations explicitly assign a type using : type.
  • Inference automatically determines types from assigned values.
  • Function parameters should usually be explicitly annotated.