Conditional Types π€©
νμ
μ€ν¬λ¦½νΈμμ μ‘°κ±΄λΆ νμ
μ T extends U ? X : Y
μ κ°μ ννλ‘ μ¬μ©λλ€. μ΄λ T
κ° U
μ ν λΉ κ°λ₯νμ§μ λ°λΌμ X
μ Y
μ€ νλμ νμ
μ μ ννκ² λλ€.
μ΄λ¬ν λͺ¨μ΅μ κΈ°μ‘΄ javascriptμ μΌνμ°μ°μμ μ μ¬νκ² λκ»΄μ§λ€. (condition ? trueExpression : falseExpression)
interface Animal {
live(): void
}
interface Dog extends Animal {
woof(): void
}
type Example1 = Dog extends Animal ? number : string // type Example1 = number
type Example2 = RegExp extends Animal ? number : string // type Example2 = string
Genericκ³Ό ν¨κ» μ¬μ©νκΈ°
Genericκ³Ό ν¨κ» μ¬μ©νλ©΄ λ μ μ©νκ² μ¬μ©ν μ μλ€. λ€μ μμ λ₯Ό 보μ.
// μμ 1
type MessageOf<T> = T extends { message: unknown } ? T["message"] : never
interface Email {
message: string
}
interface Dog {
bark(): void
}
type EmailMessageContents = MessageOf<Email> // string
type DogMessageContents = MessageOf<Dog> // never
// μμ 2
type Flatten<T> = T extends any[] ? T[number] : T
// Extracts out the element type.
type Str = Flatten<string[]> // type Str = string
// Leaves the type alone.
type Num = Flatten<number> // type Num = number
Inferμ ν¨κ» μ¬μ©νκΈ°
infer
λ νμ
μ€ν¬λ¦½νΈμμ νμ
μ μΆλ‘ νλ ν€μλμ΄λ€. infer
λ₯Ό μ¬μ©νλ©΄ μ‘°κ±΄λΆ νμ
μ μ¬μ©ν΄ λμ μΌλ‘ νμ
μ μΆλ‘ ν λ μ μ©νκ² μ¬μ©ν μ μλ€.
// μμ1
type Flatten<Type> = Type extends Array<infer Item> ? Item : Type
//μμ2
type GetReturnType<Type> = Type extends (...args: never[]) => infer Return
? Return
: never
type Num = GetReturnType<() => number> // number
type Str = GetReturnType<(x: string) => string> // string
type Bools = GetReturnType<(a: boolean, b: boolean) => boolean[]> // boolean[]
μμ 2λ₯Ό 보면 ν¨μμ λ°ννμ μ λμ μΌλ‘ λ³κ²½ν μ μκ² inferλ₯Ό μ΄μ©ν΄ μΆλ‘ ν μμ λ€.
Distributive Conditional Types
Distributive Conditional Typesλ μ‘°κ±΄λΆ νμ
μ΄ μ¬μ©λ λ μ λ¬λλ νμ
μ΄ union
μΌλ‘ ꡬμ±λμ΄ μμΌλ©΄ κ°κ°μ νμ
μ μ‘°κ±΄λΆ νμ
μ μ μ©ν ν union
μΌλ‘ λ€μ ν©μ³μ§λ€.
type ToArray<Type> = Type extends any ? Type[] : never
type StrArrOrNumArr = ToArray<string | number> // string[] | number[]