|
| 1 | +--- |
| 2 | +title: Indexed Access Types |
| 3 | +layout: docs |
| 4 | +permalink: /docs/handbook/2/indexed-access-types.html |
| 5 | +oneline: "Using Type['a'] syntax to access a subset of a type." |
| 6 | +--- |
| 7 | + |
| 8 | +We can use an _indexed access type_ to look up a specific property on another type: |
| 9 | + |
| 10 | +```ts twoslash |
| 11 | +type Person = { age: number; name: string; alive: boolean }; |
| 12 | +type Age = Person["age"]; |
| 13 | +// ^? |
| 14 | +``` |
| 15 | + |
| 16 | +The indexing type is itself a type, so we can use unions, `keyof`, or other types entirely: |
| 17 | + |
| 18 | +```ts twoslash |
| 19 | +type Person = { age: number; name: string; alive: boolean }; |
| 20 | +// ---cut--- |
| 21 | +type I1 = Person["age" | "name"]; |
| 22 | +// ^? |
| 23 | + |
| 24 | +type I2 = Person[keyof Person]; |
| 25 | +// ^? |
| 26 | + |
| 27 | +type AliveOrName = "alive" | "name"; |
| 28 | +type I3 = Person[AliveOrName]; |
| 29 | +// ^? |
| 30 | +``` |
| 31 | + |
| 32 | +You'll even see an error if you try to index a property that doesn't exist: |
| 33 | + |
| 34 | +```ts twoslash |
| 35 | +// @errors: 2339 |
| 36 | +type Person = { age: number; name: string; alive: boolean }; |
| 37 | +// ---cut--- |
| 38 | +type I1 = Person["alve"]; |
| 39 | +``` |
| 40 | + |
| 41 | +Another example of indexing with an arbitrary type is using `number` to get the type of an array's elements. |
| 42 | +We can combine this with `typeof` to conveniently capture the element type of an array literal: |
| 43 | + |
| 44 | +```ts twoslash |
| 45 | +const MyArray = [ |
| 46 | + { name: "Alice", age: 15 }, |
| 47 | + { name: "Bob", age: 23 }, |
| 48 | + { name: "Eve", age: 38 }, |
| 49 | +]; |
| 50 | + |
| 51 | +type Person = typeof MyArray[number]; |
| 52 | +// ^? |
| 53 | +type Age = typeof MyArray[number]["age"]; |
| 54 | +// ^? |
| 55 | +// Or |
| 56 | +type Age2 = Person["age"]; |
| 57 | +// ^? |
| 58 | +``` |
| 59 | + |
| 60 | +You can only use types when indexing, meaning you can't use a `const` to make a variable reference: |
| 61 | + |
| 62 | +```ts twoslash |
| 63 | +// @errors: 2538 2749 |
| 64 | +type Person = { age: number; name: string; alive: boolean }; |
| 65 | +// ---cut--- |
| 66 | +const key = "age"; |
| 67 | +type Age = Person[key]; |
| 68 | +``` |
| 69 | + |
| 70 | +However, you can use a type alias for a similar style of refactor: |
| 71 | + |
| 72 | +```ts twoslash |
| 73 | +type Person = { age: number; name: string; alive: boolean }; |
| 74 | +// ---cut--- |
| 75 | +type key = "age"; |
| 76 | +type Age = Person[key]; |
| 77 | +``` |
0 commit comments