Execute Program

Everyday TypeScript: Indexing Into Tuple and Array Types

Welcome to the Indexing Into Tuple and Array Types lesson!

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

  • We've seen a way to access the types of individual properties with SomeType['someProperty']. We can do the same thing for tuple and array types.

  • >
    type HostnameAndPort = [string, number];
    const hostname: HostnameAndPort[0] = 'localhost';
    const port: HostnameAndPort[1] = 5432;
    const hostnameAndPort: HostnameAndPort = [hostname, port];
    hostnameAndPort;
    Result:
    ['localhost', 5432]Pass Icon
  • If we try to access a tuple type index that doesn't exist, that's a type error.

  • >
    type HostnameAndPort = [string, number];
    const hostname: HostnameAndPort[2] = undefined;
    hostname;
    Result:
    type error: Tuple type 'HostnameAndPort' of length '2' has no element at index '2'.Pass Icon
  • Arrays support the same type indexing as tuples. But arrays are simpler: TypeScript lets us index the type with any number. We always get the same type back.

  • >
    type Names = string[];
    const usernames: Names = ['amir', 'betty'];
    const username: Names[0] = 'cindy';
    username;
    Result:
    'cindy'Pass Icon
  • >
    type Names = string[];
    const usernames: Names = ['amir', 'betty'];
    const username: Names[999999] = 'dalili';
    username;
    Result:
    'dalili'Pass Icon
  • In fact, we don't have to index with a specific number at all! We can use number itself as the index, like Names[number]. When we write Names[0] or Names[999999], that implies that the index matters. Asking for Names[number] makes it clear that the index doesn't actually matter because all of the array's elements have the same type.

  • >
    type Names = string[];
    const usernames: Names = ['amir', 'betty'];
    const username: Names[number] = 'ebony';
    username;
    Result:
    'ebony'Pass Icon
  • Here's a code problem:

    The code below defines a NameAndAge tuple type. It also defines a function, but the function's parameter types are missing.

    Add this function's parameter types, but don't enter them as string and number. Instead, declare the parameter types by indexing into the tuple type.

    type NameAndAge = [string, number];
    function userToString(name: NameAndAge[0], age: NameAndAge[1]) {
    return `${name} (age ${age})`;
    }
    userToString('Amir', 36);
    Goal:
    'Amir (age 36)'
    Yours:
    'Amir (age 36)'Pass Icon