TypeScript에서는 유형 변환에 도움을 주는 전역으로 사용 가능한 유틸리티 타입을 제공한다.
TypeScript의 여러 유틸리티 타입에 대해 알아본다.
Partial<Type>Type의 모든 속성을 선택적 (?) 으로 변경한 새로운 타입을 반환한다. (↔ Required<Type>)
1interface User {2 name: string;3 age: number;4}5
6const userA: User = {7 name: "Jongmin",8};9// TS2741: Property 'age' is missing in type '{ name: string; }' but required in type 'IUser'.10
11const userB: Partial<User> = {12 name: "Jongmin",13};Partial<User> 은 다음처럼 이해 할 수 있다.
1interface NewType {2 name?: string;3 age?: number;4}Readonly<Type>Type의 모든 속성을 읽기 전용(readonly)로 설정한 타입을 구성한다.
1interface User {2 name: string;3}4
5const userA: Readonly<User> = {6 name: "Jongmin",7};8
9userA.name = "Minjong";10// error TS2540: Cannot assign to 'name' because it is a read-only property.Record<Keys,Type>타입 Type의 속성 집합 Keys로 타입을 구성한다.
1interface StudentInfo {2 age: number;3 graduated: boolean;4}5
6type Student = "Kim" | "Lee" | "Park";7
8const x: Record<Student, StudentInfo> = {9 Kim: { age: 21, graduated: false },10 Lee: { age: 26, graduated: true },11 Park: { age: 24, graduated: false },12};위의 Record<K,T> 는 다음과 같이 이해 할 수 있다.
1interface NewType {2 Kim: { age: number; graduated: boolean };3 Lee: { age: number; graduated: boolean };4 Park: { age: number; graduated: boolean };5}Pick<Type,Keys>Type에서 속성 Keys의 집합을 선택해서 타입을 구성한다.
1interface UserInfo {2 name: string;3 age: number;4 graduated: boolean;5}6
7type Keys = "name" | "email";8
9const user: Pick<UserInfo, Keys> = {10 name: "Lee Jongmin",11 age: 26,12 graduated: true, // error TS2322: Type '{ name: string; age: number; graduated: boolean; }' is not assignable to type 'Pick<UserInfo, Key>'.13};위의 Pick<UserInfo,Keys> 는 다음과 같이 이해 할 수 있다.
1interface NewType {2 name: string;3 age: number;4}Omit<Type,Keys>Type의 모든 프로퍼티를 선택한 다음 Keys를 제거한 타입을 구성한다.
1interface UserInfo {2 name: string;3 age: number;4 gender: string;5}6
7type GenderPrivate = Omit<UserInfo, "gender">;8
9const user: GenderPrivate = {10 name: "Jongmin",11 age: 26,12};Exclude<T1,T2>T1에서 T2를 제외한 타입을 구성한다. (T1 - T2)로 이해 할 수 있다.
1type T1 = "a" | "b" | "c" | "d";2type T2 = "c" | "d";3
4type T3 = Exclude<T1, T2>; // 'a'|'b'Extract<T1,T2>T1에서 T2에 할당 할 수 있는 모든 속성을 추출해 타입을 구성한다. (T1 ∩ T2)로 이해 할 수 있다.
1type T1 = Extract<"a" | "b" | "c", "a" | "d">; // 'a'2type T2 = Extract<string | number, boolean>; // neverNonNullable<Type>Type에서 null과 undefined를 제외한 새로운 타입을 반환한다.
1type T = string | null | undefined;2
3const a: T = null;4const b: NonNullable<T> = null; // error TS2322: Type 'null' is not assignable to type 'string'.Parameters<Type>함수 타입 Type의 매개변수 타입들의 튜플 타입을 구성한다.
1declare function f1(arg: { a: number; b: string }): void;2type T0 = Parameters<() => string>; // []3type T1 = Parameters<(s: string) => void>; // [s: string]4type T2 = Parameters<<T>(arg: T) => T>; // [arg: unknown]5type T4 = Parameters<typeof f1>; // [arg: { a: number, b: string }]6type T5 = Parameters<any>; // unknown[]7type T6 = Parameters<never>; // never8type T7 = Parameters<string>; // Type 'string' does not satisfy the constraint '(...args: any) => any'.9type T8 = Parameters<Function>; // Type 'Function' does not satisfy the constraint '(...args: any) => any' Type 'Function' provides no match for the signature '(...args: any): any'.ConstructorParameters<Type>클래스 Type의 매개변수 타입을 새로운 튜플 타입으로 구성한다. (Type가 함수가 아닌 경우 never을 생성)
1type T0 = ConstructorParameters<ErrorConstructor>; // [message?: string]2type T1 = ConstructorParameters<FunctionConstructor>; // string[]3type T2 = ConstructorParameters<RegExpConstructor>; // [pattern: string | RegExp, flags?: string]4type T3 = ConstructorParameters<any>; // unknown[]5type T4 = ConstructorParameters<Function>; // Type 'Function' does not satisfy the constraint 'abstract new (...args: any) => any'. Type 'Function' provides no match for the signature 'new (...args: any): any'.ReturnType<Type>함수 Type의 반환 타입으로 구성된 타입을 구성한다.
1declare function f1(): { a: number; b: string };2type T0 = ReturnType<() => string>; // string3type T1 = ReturnType<(s: string) => void>; // void4type T2 = ReturnType<<T>() => T>; // unknown5type T3 = ReturnType<<T extends U, U extends number[]>() => T>; // number[]6type T4 = ReturnType<typeof f1>; // { a: number, b: string }7type T5 = ReturnType<any>; // any8type T6 = ReturnType<never>; // never9type T7 = ReturnType<string>; // Type 'string' does not satisfy the constraint '(...args: any) => any'.10type T8 = ReturnType<Function>; // Type 'Function' does not satisfy the constraint '(...args: any) => any'. Type 'Function' provides no match for the signature '(...args: any): any'.InstanceType<Type>생성자 함수 타입 Type의 인스턴스 타입으로 구성된 타입을 구성한다.
1class C {2 x = 0;3 y = 0;4}5
6type T0 = InstanceType<typeof C>; // C7type T1 = InstanceType<any>; // any8type T2 = InstanceType<never>; // never9type T3 = InstanceType<string>; // Type 'string' does not satisfy the constraint 'abstract new (...args: any) => any'.10type T4 = InstanceType<Function>; // Type 'Function' does not satisfy the constraint 'abstract new (...args: any) => any'. Type 'Function' provides no match for the signature 'new (...args: any): any'.Required<Type>Type의 모든 프로퍼티가 필수로 설정된 타입을 구성한다. (↔ Partial<Type>)
1interface User {2 name?: string;3 age?: number;4}5
6const userA: Required<User> = {7 name: "Jongmin",8};9// TS2741: Property 'age' is missing in type '{ name: string; }' but required in type 'Required<User>'.Required<User> 은 다음처럼 이해 할 수 있다.
1interface NewType {2 name: string;3 age: number;4}ThisParameterType<Type>함수 Type의 명시적 this 매개변수 타입을 새로운 타입으로 반환한다. (this 매개변수가 없을 경우 unknown을 반환)
1function toHex(this: Number) {2 return this.toString(16);3}4
5function numberToString(n: ThisParameterType<typeof toHex>) {6 return toHex.apply(n);7}8
9// toHex의 명시적 this 타입인 Number를 참고해서 numberToString의 매개변수 n을 선언함.OmitThisParameter<Type>함수 Type에서 this 매개변수를 제거한다.
1function toHex(this: Number) {2 return this.toString(16);3}4
5const fiveToHex: OmitThisParameter<typeof toHex> = toHex.bind(5);6
7console.log(fiveToHex()); // 5ThisType<Type>Type의 this 컨텍스트를 명시하는 역할을 하며 별도의 타입을 반환하지 않는다.