Skip to content

Commit 8ad1f19

Browse files
committed
add original doc
1 parent 9819f47 commit 8ad1f19

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
---
2+
title: Keyof Type Operator
3+
layout: docs
4+
permalink: /docs/handbook/2/keyof-types.html
5+
oneline: "Using the keyof operator in type contexts."
6+
---
7+
8+
## The `keyof` type operator
9+
10+
The `keyof` operator takes an object type and produces a string or numeric literal union of its keys.
11+
The following type P is the same type as "x" | "y":
12+
13+
```ts twoslash
14+
type Point = { x: number; y: number };
15+
type P = keyof Point;
16+
// ^?
17+
```
18+
19+
If the type has a `string` or `number` index signature, `keyof` will return those types instead:
20+
21+
```ts twoslash
22+
type Arrayish = { [n: number]: unknown };
23+
type A = keyof Arrayish;
24+
// ^?
25+
26+
type Mapish = { [k: string]: boolean };
27+
type M = keyof Mapish;
28+
// ^?
29+
```
30+
31+
Note that in this example, `M` is `string | number` -- this is because JavaScript object keys are always coerced to a string, so `obj[0]` is always the same as `obj["0"]`.
32+
33+
`keyof` types become especially useful when combined with mapped types, which we'll learn more about later.

0 commit comments

Comments
 (0)