Execute Program

TypeScript Basics: Arrays

Welcome to the Arrays lesson!

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

  • Array types are marked with []. An array of numbers is number[].

  • >
    let numbers: number[] = [1, 2, 3];
    numbers[1];
    Result:
    2Pass Icon
  • Arrays can contain any type: boolean[] is an array of booleans, etc.

  • >
    let bools: boolean[] = [true, false];
    bools[1];
    Result:
    falsePass Icon
  • The type boolean[] has two parts. Overall, it's an array. But inside the array, there are booleans.

  • For now, we'll only consider arrays that hold exactly one type, like boolean[] or string[]. Later, we'll see arrays with mixed types, like an array of strings and numbers.

  • The next example contains a type error: our variable is a string[], but we try to put a 3 inside the array.

  • >
    let strings: string[] = ['a', 'b', 3];
    strings;
    Result:
    type error: Type 'number' is not assignable to type 'string'.Pass Icon
  • Remember that types are always checked. Assigning to a new variable preserves the type, even if it's inferred.

  • >
    let strings: string[] = ['a', 'b', 'c'];
    let values = strings;
    values;
    Result:
    ['a', 'b', 'c']Pass Icon
  • >
    let strings: string[] = ['a', 'b', 'c'];
    let values = strings;
    let numbers: number[] = values;
    numbers;
    Result:
    type error: Type 'string[]' is not assignable to type 'number[]'.
      Type 'string' is not assignable to type 'number'.Pass Icon