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]
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'.
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'
>
type Names = string[];const usernames: Names = ['amir', 'betty'];const username: Names[999999] = 'dalili';username;Result:
'dalili'
In fact, we don't have to index with a specific number at all! We can use
numberitself as the index, likeNames[number]. When we writeNames[0]orNames[999999], that implies that the index matters. Asking forNames[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'
Here's a code problem:
The code below defines a
NameAndAgetuple 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
stringandnumber. 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)'