You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
At the heart of most useful programs, we have to make decisions based on input.
9
-
JavaScript programs are no different, but given the fact that values can be easily introspected, those decisions are also based on the types of the inputs.
10
-
_Conditional types_ help describe the relation between the types of inputs and outputs.
8
+
대부분 유용한 프로그램의 핵심은, 입력에 따라 결정할 수 있어야 합니다.
9
+
JavaScript 프로그램도 비슷하게 값들이 쉽게 검토될 수 있다는 사실을 고려할 때, 이러한 결정들 또한 입력에 한 종류로 볼 수 있습니다.
10
+
_조건부 타입_ 은 입력과 출력 타입간의 관계를 설명하는 데 도움을 줄 수 있습니다.
11
11
12
12
```ts twoslash
13
13
interfaceAnimal {
@@ -24,7 +24,7 @@ type Example2 = RegExp extends Animal ? number : string;
24
24
// ^?
25
25
```
26
26
27
-
Conditional types take a form that looks a little like conditional expressions (`condition ? trueExpression : falseExpression`) in JavaScript:
27
+
조건부 타입은 JavaScript에 있는 삼항 연산자 조건문 (`condition ? trueExpression : falseExpression`) 같은 형태를 가집니다.
28
28
29
29
```ts twoslash
30
30
typeSomeType=any;
@@ -36,12 +36,12 @@ type Stuff =
36
36
SomeTypeextendsOtherType?TrueType:FalseType;
37
37
```
38
38
39
-
When the type on the left of the `extends` is assignable to the one on the right, then you'll get the type in the first branch (the "true" branch); otherwise you'll get the type in the latter branch (the "false" branch).
39
+
`extends`를 기준으로 왼쪽에 있는 타입이 오른쪽 타입에 할당할 수 있다면 첫 번째 분기(참값 분기)를, 그렇지 않다면 뒤의 분기(거짓값 분기)를 얻게 됩니다.
40
40
41
-
From the examples above, conditional types might not immediately seem useful - we can tell ourselves whether or not `Dog extends Animal`and pick`number` or `string`!
42
-
But the power of conditional types comes from using them with generics.
41
+
`Dog extends Animal`에 따라`number`나 `string`인지 알려주는 것 말곤, 위의 예제에서 조건부 타입은 그다지 유용해 보이지 않습니다!
42
+
하지만 제네릭과 함께 사용될 때 조건부 타입은 강력한 힘을 갖습니다.
43
43
44
-
For example, let's take the following `createLabel`function:
These overloads for createLabel describe a single JavaScript function that makes a choice based on the types of its inputs. Note a few things:
62
+
createLabel의 오버로드들은 입력 타입에 따른 단일 JavaScript 함수를 나타냅니다. 다음을 주목하세요.
63
63
64
-
1.If a library has to make the same sort of choice over and over throughout its API, this becomes cumbersome.
65
-
2.We have to create three overloads: one for each case when we're _sure_ of the type (one for `string` and one for `number`), and one for the most general case (taking a `string | number`). For every new type `createLabel` can handle, the number of overloads grows exponentially.
64
+
1.만약 라이브러리가 매번 API 전체에서 비슷한 종류의 함수를 만들어야 한다면 번거로워집니다.
65
+
2.우린 3가지 오버로드 즉, 각 케이스별로 _확실한_ 타입을 가지거나 (각각 `number`와 `string`) 그리고 일반적인 케이스(`string | number`) 가져야 합니다. `createLabel`의 새로운 타입을 다루기 위해선 오버로드의 수는 기하급수적으로 증가합니다.
66
66
67
-
Instead, we can encode that logic in a conditional type:
67
+
대신에 조건부 타입으로 로직을 인코딩할 수 있습니다.
68
68
69
69
```ts twoslash
70
70
interfaceIdLabel {
@@ -79,7 +79,7 @@ type NameOrId<T extends number | string> = T extends number
79
79
:NameLabel;
80
80
```
81
81
82
-
We can then use that conditional type to simplify our overloads down to a single function with no overloads.
82
+
조건부 타입을 사용하면 단일 함수까지 오버로드 없이 단순화 시킬 수 있습니다.
83
83
84
84
```ts twoslash
85
85
interfaceIdLabel {
@@ -106,20 +106,20 @@ let c = createLabel(Math.random() ? "hello" : 42);
106
106
// ^?
107
107
```
108
108
109
-
### Conditional Type Constraints
109
+
### 조건부 타입으로 제한하기
110
110
111
-
Often, the checks in a conditional type will provide us with some new information.
112
-
Just like with narrowing with type guards can give us a more specific type, the true branch of a conditional type will further constrain generics by the type we check against.
111
+
종종, 조건부 타입의 검사에서 새로운 정보를 얻을 수 있습니다.
112
+
타입 가드가 더 구체적인 타입으로 좁혀주듯이, 조건부 타입의 참값 분기는 대조하는 타입에 따라서 제네릭을 더 제한할 수 있습니다.
113
113
114
-
For example, let's take the following:
114
+
다음 예를 살펴보겠습니다.
115
115
116
116
```ts twoslash
117
117
// @errors: 2536
118
118
typeMessageOf<T> =T["message"];
119
119
```
120
120
121
-
In this example, TypeScript errors because `T` isn't known to have a property called `message`.
122
-
We could constrain `T`, and TypeScript would no longer complain:
121
+
위 에제에서, `T`가 `message` 프로퍼티를 가지고 있는지 알 수 없기 때문에 TypeScript에서 오류가 발생합니다.
122
+
`T`의 타입을 제한해서 TypeScript가 더이상 오류를 내지 않도록 만들 수 있습니다.
Here, we used the `infer` keyword to declaratively introduce a new generic type variable named `Item` instead of specifying how to retrieve the element type of `T` within the true branch.
188
-
This frees us from having to think about how to dig through and probing apart the structure of the types we're interested in.
187
+
여기서 참값 분기에서 `T`의 요소 타입을 어떻게 제시할 필요 없이, `infer` 키워드를 새 제네릭 타입 변수 `Item`에 선언적으로 사용했습니다.
188
+
이 방식은 관심 있는 타입의 구조를 깊게 분석하지 않아도 되도록 만들어줍니다.
189
189
190
-
We can write some useful helper type aliases using the `infer` keyword.
191
-
For example, for simple cases, we can extract the return type out from function types:
When inferring from a type with multiple call signatures (such as the type of an overloaded function), inferences are made from the _last_ signature (which, presumably, is the most permissive catch-all case). It is not possible to perform overload resolution based on a list of argument types.
208
+
여러 호출 시그니처 (오버로트 함수 타입 같이)를 가진 타입을 추론할 때, _마지막_ 시그니처 (아마, 모든 케이스에 허용되는)로 추론하게 됩니다. 인자 타입의 목록에 기반해서 오버로드들을 처리할 수는 없습니다.
209
209
210
210
```ts twoslash
211
211
declarefunction stringOrNum(x:string):number;
@@ -216,16 +216,16 @@ type T1 = ReturnType<typeof stringOrNum>;
216
216
// ^?
217
217
```
218
218
219
-
## Distributive Conditional Types
219
+
## 분산적인 조건부 타입
220
220
221
-
When conditional types act on a generic type, they become _distributive_ when given a union type.
222
-
For example, take the following:
221
+
제네릭 타입 위에서 조건부 타입은 유니언 타입을 만나면 _분산적으로_ 동작합니다.
222
+
예를 들어 다음을 보겠습니다.
223
223
224
224
```ts twoslash
225
225
typeToArray<Type> =Typeextendsany?Type[] :never;
226
226
```
227
227
228
-
If we plug a union type into `ToArray`, then the conditional type will be applied to each member of that union.
228
+
`ToArray`에 유니언 타입을 넘기면 조건부 타입은 유니언의 각 멤버에 적용됩니다.
229
229
230
230
```ts twoslash
231
231
typeToArray<Type> =Typeextendsany?Type[] :never;
@@ -234,15 +234,15 @@ type StrArrOrNumArr = ToArray<string | number>;
234
234
// ^?
235
235
```
236
236
237
-
What happens here is that `StrArrOrNumArr` distributes on:
237
+
`StrArrOrNumArr`이 동작하는 방식은 다음과 같습니다.
238
238
239
239
```ts twoslash
240
240
typeStrArrOrNumArr=
241
241
// ---cut---
242
242
string|number;
243
243
```
244
244
245
-
and maps over each member type of the union, to what is effectively:
245
+
유니언의 각 멤버 타입은 효율적으로 매핑됩니다.
246
246
247
247
```ts twoslash
248
248
typeToArray<Type> =Typeextendsany?Type[] :never;
@@ -251,16 +251,15 @@ type StrArrOrNumArr =
251
251
ToArray<string> |ToArray<number>;
252
252
```
253
253
254
-
which leaves us with:
254
+
그리고 다음과 같이 결과가 나옵니다.
255
255
256
256
```ts twoslash
257
257
typeStrArrOrNumArr=
258
258
// ---cut---
259
259
string[] |number[];
260
260
```
261
261
262
-
Typically, distributivity is the desired behavior.
263
-
To avoid that behavior, you can surround each side of the `extends` keyword with square brackets.
262
+
일반적으로 분산성이 원하는 동작입니다. 이러한 동작을 방지하려면 `extends`키워드의 양 옆을 대괄호로 감싸면 됩니다.
0 commit comments