Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update Indexed Access Types.md #2603

Open
wants to merge 2 commits into
base: v2
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -57,17 +57,21 @@ type Age2 = Person["age"];
// ^?
```

You can only use types when indexing, meaning you can't use a `const` to make a variable reference:
When indexing, you cannot use types that are wider than the keys of the object being indexed, so pay attention of the variable's type used to index.
For example, when using `const` to make a variable reference, pay attention that its type is `string` and not `"age"` (this can be changed by using [`as const`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#const-assertions):

```ts twoslash
// @errors: 2538 2749
type Person = { age: number; name: string; alive: boolean };
// ---cut---
const key = "age";
type Age = Person[key];
const key = "age"; // The type is 'string', which is too wide (e.g. "foo" is also a string, but not one of Person's keys), so the next line won't compile
type Age1 = Person[key];

const keyWithConstantType = "age" as const; // Type is "age", which is a key in Person, so that will work
type Age2 = Person[keyWithConstantType];
```

However, you can use a type alias for a similar style of refactor:
Moreover, you can use a type alias for a similar style of refactor:

```ts twoslash
type Person = { age: number; name: string; alive: boolean };
Expand Down