TypeScript - Utility Types 3

CH_Hwang·2022년 7월 22일
0

TypeScript

목록 보기
12/12

NonNullable

NonNullable<Type>은 Type에서 null이나 undefined를 제외한 타입을 추출한다.

type a = NonNullable<string || number || undefined || null>;
console.log(typeof a); // string || number

Parameters

Parameters<Type>은 함수의 파라미터의 타입을 tuple타입으로 추출한다.

declare function f1(arg: { a: number; b: string }): void;

type T0 = Parameters<() => string>;
console.log(typeof T0) // []

type T1 = Parameters<(s: string) => void>;
console.log(typeof T1) // [s: string]

type T2 = Parameters<typeof f1>;
console.log(typeof T2) // [arg: { a: number; b: string; }]

ConstructorParameters

ConstructorParameters<Type>은 생성자 함수의 파라미터 타입을 tuple타입이나 array타입으로 추출한다.

type T0 = ConstructorParameters<ErrorConstructor>;
console.log(T0) // [message?: string]

ReturnType

ReturnType<Type>은 함수의 return type을 추출한다.

type T0 = ReturnType<()=>string>;
console.log(typeof T0) // string

InstanceType

InstanceType<Type>은 객체 인스턴스의 타입을 추출한다.

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

type T0 = InstanceType<typeof C>
console.log(typeof T0) // C

0개의 댓글