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

Explain keyof before it first appears in a snippet #3243

Open
wants to merge 6 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 @@ -316,8 +316,17 @@ loggingIdentity({ length: 10, value: 3 });
## Using Type Parameters in Generic Constraints

You can declare a type parameter that is constrained by another type parameter.
For example, here we'd like to get a property from an object given its name.
We'd like to ensure that we're not accidentally grabbing a property that does not exist on the `obj`, so we'll place a constraint between the two types:
For example, let's say we’d like to get a property from an object given its name.
We’d like to ensure that we’re not accidentally grabbing a property that does not exist on the `obj`.
To do this, we use the `keyof` operator, which we'll cover in depth later.
For now it's enough to know that `keyof` produces the union of the keys of an object type:

```ts twoslash
type Dimension = keyof {width: number, height: number}
// ^?
```

Here we use `Key extends keyof Type` to constrain `Key` to one of the property names in `Type`:

```ts twoslash
// @errors: 2345
Expand Down