Execute Program

TypeScript Basics: Generic Arrays

Welcome to the Generic Arrays lesson!

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

  • We saw array types written as number[]. There's another way to write them: Array<number>. This syntax with angle brackets (< and >) shows up a lot in TypeScript. The number[] form only exists because many people find it more readable. An array is an array regardless of which way we write it.

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

  • >
    let numbers: number[] = [1];
    let numbers2: Array<number> = numbers;
    numbers2;
    Result:
    [1]Pass Icon
  • >
    let numbers: Array<number> = [1];
    let numbers2: number[] = numbers;
    numbers2;
    Result:
    [1]Pass Icon
  • >
    let numbers: Array<number> = [1];
    let strings: Array<string> = numbers;
    strings;
    Result:
    type error: Type 'number[]' is not assignable to type 'string[]'.
      Type 'number' is not assignable to type 'string'.Pass Icon
  • Array types like Array<number> are an example of generics. We can think of Array as a type with a "hole" in it. An array of numbers, Array<number>, fills the hole with the number type. An array of strings, Array<string>, fills the hole with the string type.

  • There's nothing special about arrays of numbers or arrays of strings. We can put any type in the hole, with no restrictions whatsoever.

  • >
    let bools: Array<boolean> = [true, false];
    bools[0];
    Result:
    truePass Icon
  • The array elements can be complex, as in arrays of arrays. This is the same array of arrays concept that you see in JavaScript. We're just writing its type down explicitly.

  • >
    let arrays: Array<Array<number>> = [[1, 2], [3, 4]];
    arrays[1];
    Result:
    [3, 4]Pass Icon