TypeScript, 오버로드 시그니쳐 vs 조건부 타입

다음과 같은 타입이 있다고 할때 …

interface IdLabel {
  id: number;
}

interface NameLabel {
  name: string;
}

숫자형 id 인자나 문자열 name 인자중 어떤 인자를 받느냐에 따라 구현이 달라지는 함수를 정의하기 위해 오버로드 시그니쳐 방식으로 다음처럼 함수를 정의할 수 있습니다.

function createLabel(id: number): IdLabel;
function createLabel(name: string): NameLabel;
function createLabel(nameOrId: string | number): IdLabel | NameLabel;
function createLabel(nameOrId: string | number): IdLabel | NameLabel {
  throw "unimplemented";
}

코드가 중복적이고 장황합니다. 이를 조건부 타입 방식으로 완전히 동일하게 작동하는 함수를 정의하면 다음과 같습니다.

type NameOrId<T extends number | string> = T extends number
  ? IdLabel
  : NameLabel;

function createLabel2<T extends number | string>(idOrName: T): NameOrId<T> {
  throw "unimplemented";
}

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다