조건부 타입(Conditional Type)

Tony·2023년 8월 4일
0

typescript

목록 보기
19/22

개념

  • 조건부 타입(Conditional Type)
  • 입력된 제네릭 파입에 따라 타입을 결정
  • T extends U ? X : Y

예제 코드

/**
 * 조건부 타입(Conditional Type)
 * - 입력된 제네릭 파입에 따라 타입을 결정
 * - T extends U ? X : Y
 */

class Subject {
  constructor(public readonly name: string, public readonly score: number) {}
  printName() {
    console.log(this.name);
  }
}

class EnglishSubject extends Subject {
  // ...
}

class MathSubject extends Subject {
  // ...
}

type Category = "english" | "math";

type SubjectType<T extends Category> = T extends "english"
  ? EnglishSubject
  : T extends "math"
  ? MathSubject
  : never;

export function getSubject<T extends Category>(
  category: T,
  name: string,
  score: number
): SubjectType<T> {
  switch (category) {
    case "english":
      return new EnglishSubject(name, score) as SubjectType<T>;
    case "math":
      return new MathSubject(name, score) as SubjectType<T>;
    default:
      throw new Error("Unknown category");
  }
}

const english = getSubject("english", "English", 100);

english.printName(); // English

응용

  • 위와 같이 factory method에서 제네릭을 따로 사용하지 않아도 팩토리 함수의 첫 번째 파라미터에서 자동 완성 기능을 지원받아서 입력하면 리턴타입이 자동으로 결정되게 만들 수 있다

참고

profile
움직이는 만큼 행복해진다

0개의 댓글