Skip to content

Commit e480acc

Browse files
committed
feat: translate Indexed Access Types.md in zh-CN
1 parent 7d57571 commit e480acc

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
---
2+
title: 索引访问类型
3+
layout: docs
4+
permalink: /zh/docs/handbook/2/indexed-access-types.html
5+
oneline: "使用 Type['a'] 语法来获取一个类型的子集"
6+
---
7+
8+
我们可以使用 _索引访问类型_ 来查找另一种类型的特定属性:
9+
10+
```ts twoslash
11+
type Person = { age: number; name: string; alive: boolean };
12+
type Age = Person["age"];
13+
// ^?
14+
```
15+
16+
被索引的类型本身也是一种类型,因此完全可以使用union、`keyof` 或其他类型:
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+
如果你试图索引一个不存在的属性,甚至会看到一个错误:
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+
使用任意类型索引的另一个例子是使用 `number` 来获取数组元素的类型。我们可以将其与 `typeof` 结合使用,方便地获取数组字面量元素的类型:
42+
43+
```ts twoslash
44+
const MyArray = [
45+
{ name: "Alice", age: 15 },
46+
{ name: "Bob", age: 23 },
47+
{ name: "Eve", age: 38 },
48+
];
49+
50+
type Person = typeof MyArray[number];
51+
// ^?
52+
type Age = typeof MyArray[number]["age"];
53+
// ^?
54+
// Or
55+
type Age2 = Person["age"];
56+
// ^?
57+
```
58+
59+
索引只能作用类型上面,这意味着不能使用 `const` 来建立变量引用:
60+
```ts twoslash
61+
// @errors: 2538 2749
62+
type Person = { age: number; name: string; alive: boolean };
63+
// ---cut---
64+
const key = "age";
65+
type Age = Person[key];
66+
```
67+
68+
不过,你可以使用类型别名进行类似的重构:
69+
70+
```ts twoslash
71+
type Person = { age: number; name: string; alive: boolean };
72+
// ---cut---
73+
type key = "age";
74+
type Age = Person[key];
75+
```

0 commit comments

Comments
 (0)