Execute Program

TypeScript Basics: Inference

Welcome to the Inference lesson!

This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!

  • Adding types to every variable would get tiresome. Fortunately, we can often avoid writing the types. TypeScript will determine them for us. We call this type inference, and we say that TypeScript infers types.

  • (Some of these examples cause type errors. You can answer those examples with type error.)

  • >
    let n: number = 2 + 2;
    n;
    Result:
    4Pass Icon
  • >
    let s: string = 2 + 2;
    s;
    Result:
    type error: Type 'number' is not assignable to type 'string'.Pass Icon
  • >
    let n = 2 + 2;
    n;
    Result:
    4Pass Icon
  • With type inference, the types are still enforced! It frees us from writing the types out, but it doesn't reduce safety. For example, if TypeScript knows that a value is a number, then it won't allow that value to be assigned to a string variable.

  • >
    let n = 1 + 1;
    let s: string = n;
    Result:
    type error: Type 'number' is not assignable to type 'string'.Pass Icon
  • >
    let num = 1 + 1;
    let str = 'a';
    num = num / str;
    Result:
    type error: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.Pass Icon
  • Type inference is widely used, and that's good. However, explicit types sometimes make code more clear. Types aren't only for correctness! Experienced static language users use types for clarity as well.