TS 유형 시스템의 분기: 조건부 유형 소개TS 유형 시스템의 분기: 조건부 유형 소개

TS 유형 시스템의 분기: 조건부 유형 소개

조건부 유형 제약 조건을 사용하여 검사를 기반으로 출력 구조를 해결하는 유형 논리를 만듭니다.

소개

TypeScript의 유형 시스템은 Turing-complete이며, 이 기능을 최대한 활용하는 주요 기능 중 하나는 조건부 유형입니다. JavaScript의 삼항 연산자(condition ? a : b)와 마찬가지로 조건 유형을 사용하면 유형 수준 논리를 만들 수 있습니다. T는 U ? X : 네. 이를 통해 동적인 상황 인식 유형 확인이 가능합니다.


기본 구문

조건부 유형은 유형이 다른 유형을 확장하는지 확인합니다.

type IsString<T> = T extends string ? true : false;

type A = IsString<'hello'>; // true
type B = IsString<42>;      // false

T가 U를 확장하는 조건은 “T가 U에 할당될 수 있습니까?“라고 묻습니다. 그렇다면 실제 분기로 확인하세요. 그렇지 않으면 거짓 분기입니다.


추론 키워드

infer 키워드를 사용하면 조건 내에서 유형을 추출할 수 있습니다.

type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never;

function greet() { return 'hello'; }
type G = ReturnType<typeof greet>; // string

infer R은 일치하는 위치에서 추론되는 유형 변수 R을 선언합니다. 이는 많은 유틸리티 유형의 기초입니다.


분산 조건부 유형

조건부 유형을 공용체와 함께 사용하면 각 멤버에 걸쳐 배포됩니다.

type ToArray<T> = T extends any ? T[] : never;

type Result = ToArray<string | number>;
// string[] | number[]  (not (string | number)[])

이 배포는 양쪽을 래핑하지 않는 한 자동으로 발생합니다.

type ToArrayNonDist<T> = [T] extends [any] ? T[] : never;

type Result2 = ToArrayNonDist<string | number>;
// (string | number)[]

조건문을 사용한 내장 유틸리티 유형

많은 표준 유틸리티 유형은 조건부 유형에 의존합니다.

// Exclude — removes types from a union
type T0 = Exclude<'a' | 'b' | 'c', 'a'>;
// 'b' | 'c'

// Extract — keeps only matching types
type T1 = Extract<string | number | (() => void), Function>;
// () => void

// NonNullable — removes null and undefined
type T2 = NonNullable<string | number | null | undefined>;
// string | number

‘Exclude’가 구현되는 방법은 다음과 같습니다.

type MyExclude<T, U> = T extends U ? never : T;

실제 패턴

입력에 따른 조건부 반환 유형

type AsyncResult<T> = T extends Promise<infer U> ? U : T;

async function fetchData(): Promise<string> {
  return 'data';
}

type Data = AsyncResult<ReturnType<typeof fetchData>>; // string

오버로드 없는 함수 오버로드

type StringOrNumber<T> = T extends string ? string : number;

function process<T extends string | number>(val: T): StringOrNumber<T>;
function process(val: any): any {
  return typeof val === 'string' ? val.toUpperCase() : val * 10;
}

const a = process('hello'); // string
const b = process(42);      // number

심층 조건부 유형 예

type DeepReadonly<T> = {
  readonly [K in keyof T]: T[K] extends object
    ? DeepReadonly<T[K]>
    : T[K];
};

interface User {
  name: string;
  address: { city: string; zip: number };
}

type ReadonlyUser = DeepReadonly<User>;
// { readonly name: string; readonly address: { readonly city: string; readonly zip: number } }

결론

조건부 유형은 유형 시스템의 if/else입니다. ‘추론’, 배포 및 매핑된 유형과 결합되어 컴파일 타임에 버그를 잡는 정교한 유형 변환이 가능합니다. 유형이 안전하고 자체 문서화되는 TypeScript 코드를 작성하기 위한 조건문을 마스터하세요.