본문 바로가기

카테고리 없음

[TS] TS Doc Reference 1회독 - 3

Utility Types

ConstructorParameters<Type>

생성자 함수의 파라미터를 바탕으로 튜플 또는 배열 타입을 만들어 냅니다. 만약 Type에 함수가 들어가지 않는 경우에는 never 타입이 됩니다.

class C {
  constructor(a: number, b: string) {}
}

type T = ConstructorParameters<typeof C>; // type: [a: number, b: string]

 

ReturnType<Type>

함수의 반환 타입을 가져올 수 있습니다. 단순한 제너릭 타입의 경우 unknown을 반환하고 any와 never은 any never을 다시 반환합니다.

type T = RetrunType<() => string>; // type: string

 

InstanceType<Type>

생성자 함수의 인스턴스 타입을 가져옵니다.

class C {
  x = 0;
  y = 0;
}

type T = InstanceType<typeof C>; // type: C

 

NoInfer<Type>

해당 Type 이외에는 추론되지 않도록 막아주는 타입입니다. 예를 들어 default 값을 설정할 때 타입이 벗어나지 않게 도와주는 역할을 합니다.

function f<C extends string>(val: C[], defaultVal?: NoInfer<C>) {}

f(['a', 'b', 'c'], 'c');
f(['a', 'b', 'c'], 'd'); // error

 

참고

https://www.typescriptlang.org/docs/handbook/utility-types.html