Skip to content

Commit 73f1439

Browse files
Merge pull request #142 from bumkeyy/translate-indexed-access-types-ko
Co-authored-by: yeonjuan <[email protected]>
2 parents 516b187 + 45a33fe commit 73f1439

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
---
2+
title: Indexed Access Types
3+
layout: docs
4+
permalink: /ko/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+
인덱싱된 타입은 그 자체로도 타입이라서 유니언, `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`로 인덱싱해서 배열 요소의 타입을 가져올 수 있습니다.
42+
`typeof`와 결합하면 편리하게 배열 리터럴의 요소 타입을 캡쳐할 수 있습니다.
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+
인덱싱할 때 변수 참조를 위해 사용된 `const`는 사용할 수 없고, 오로지 타입만 사용 가능합니다.
61+
62+
63+
```ts twoslash
64+
// @errors: 2538 2749
65+
type Person = { age: number; name: string; alive: boolean };
66+
// ---cut---
67+
const key = "age";
68+
type Age = Person[key];
69+
```
70+
71+
하지만, 비슷한 스타일의 리팩터로 타입 별칭을 사용할 수 있습니다.
72+
73+
```ts twoslash
74+
type Person = { age: number; name: string; alive: boolean };
75+
// ---cut---
76+
type key = "age";
77+
type Age = Person[key];
78+
```

0 commit comments

Comments
 (0)