Skip to content

Commit 77028da

Browse files
author
Orta Therox
authored
Merge pull request #81 from yahma25/Translation-to-ko-playground-Discriminate-Types
Translate 1 file to ko. playground-Discriminate Types
2 parents 43e7399 + a50c3e4 commit 77028da

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
// 식별된 타입 유니언은
2+
// 잠재적인 객체의 집합을 하나의 특별한 객체로 줄이기 위해
3+
// 코드 흐름 분석을 사용하는 것입니다.
4+
//
5+
// 이 패턴은
6+
// 다른 문자열 또는 숫자 상수를 가진
7+
// 비슷한 객체 집합에 대해 잘 동작합니다
8+
// 예: 이벤트로 지어진 목록, 또는 버전이 매겨진 객체의 집합
9+
10+
type TimingEvent = { name: "start"; userStarted: boolean } | { name: "closed"; duration: number };
11+
12+
// 이벤트가 이 함수에 들어왔을 때,
13+
// 두 가지 잠재적인 타입 중의 하나가 될 수 있습니다.
14+
15+
const handleEvent = (event: TimingEvent) => {
16+
// event.name에 비교하는 swtich문을 사용하여
17+
// TypeScript의 코드 흐름 분석은
18+
// 객체가 유니언 중 하나의 타입에 의해서만 표현될 수 있다는 것을 알아낼 수 있습니다.
19+
20+
switch (event.name) {
21+
case "start":
22+
// 이름이 "start"인
23+
// TimingEvent 내부의 유일한 타입이기 때문에
24+
// userStarted에 안전하게 접근할 수 있다는 것을 의미합니다.
25+
const initiatedByUser = event.userStarted;
26+
break;
27+
28+
case "closed":
29+
const timespan = event.duration;
30+
break;
31+
}
32+
};
33+
34+
// 이 패턴은 식별자로써 사용할 수 있는
35+
// 숫자와 같습니다.
36+
37+
// 이 예제에서,
38+
// 식별된 유니언과 처리해야 하는 추가 오류 상태가 있습니다.
39+
40+
type APIResponses = { version: 0; msg: string } | { version: 1; message: string; status: number } | { error: string };
41+
42+
const handleResponse = (response: APIResponses) => {
43+
// 오류 케이스를 처리하고 반환하세요
44+
if ("error" in response) {
45+
console.error(response.error);
46+
return;
47+
}
48+
49+
// 이제 TypeScript는 APIResponse가
50+
// 오류 타입이 될 수 없다는 사실을 알고 있습니다.
51+
// 오류가 있었다면, 함수는 반환했을 것입니다.
52+
// 아래의 response에 호버하여 확인해볼 수 있습니다.
53+
54+
if (response.version === 0) {
55+
console.log(response.msg);
56+
} else if (response.version === 1) {
57+
console.log(response.status, response.message);
58+
}
59+
};
60+
61+
// 유니언의 모든 부분이 확인되었다는 것을 보장할 수 있으니
62+
// if문 대신에 switch문을 사용하는 것이 더 낫습니다.
63+
// 핸드북에 never 타입을 사용하는
64+
// 좋은 패턴이 있습니다:
65+
66+
// https://www.typescriptlang.org/docs/handbook/advanced-types.html#discriminated-unions

0 commit comments

Comments
 (0)