[Typescript] 유틸리티 타입 12가지 사용하기

• TypeScript는 공통 타입 변환을 용이하게 하기 위해 유틸리티 타입을 제공한다.
• 유틸리티 타입은 전역으로 사용 가능하다.
종류
- Partial
- Readonly
- Record
- Pick
- Omit
- Exclude
- Extract
- NonNullable
- Parameter
- ConstructorParameters
- ReturnType
- Required
1. Partial
interface Todo {
title: string;
description: string;
}
function updateTodo(todo: Todo, fieldsToUpdate: Partial<Todo>) {
return { ...todo, ...fieldsToUpdate };
}
const todo1 = {
title: 'organize desk',
description: 'clear clutter',
};
const todo2 = updateTodo(todo1, {
description: 'throw out trash',
});
-
프로퍼티를 선택적으로 만드는 타입을 구성한다.
-
주어진 타입의 모든 하위 타입 집합을 나타내는 타입을 반환한다.
2. Readonly
interface Todo {
title: string;
}
const todo: Readonly<Todo> = {
title: 'Delete inactive users',
};
// 사용 예: frozen 객체의 프로퍼티에 재할당 방지
todo.title = 'Hello';
// Error: Cannot as sign to 'title' because it is a read-only property
프로퍼티를 읽기 전용(readonly)으로 설정한 타입 을 구성한다.
객체 생성시 프로퍼티 값을 바꿀 수 없다.
프로퍼티를 위해 사용할 수 있는 const이다.
3. Record<T,K>
interface PageInfo {
title: string;
}
type Page = 'home' | 'about' | 'contact';
const x: Record<Page, PageInfo> = {
about: { title: 'about' },
contact: { title: 'contact' },
home: { subTitile: 'home' },
// Error: '{ subTitile: string; }' is not assignable
main: { title: 'home' },
// Error: main is not assignable to type 'Page'.
};
프로퍼티의 집합 K로 타입을 구성한다.
타입의 프로퍼티들을 다른 타입에 매핑시키는 데 사용한다.
4. Pick<T,K>
interface Todo {
title: string;
description: string;
completed: boolean;
}
type TodoPreview = Pick<Todo, 'title' | 'completed'>;
const todo: TodoPreview = {
title: 'Clean room',
completed: false,
description: 'description’
// Error: 'description' is not assignable to type
};
프로퍼티 K의 집합을 선택해 타입을 구성한다
5. Omit<T,K>
interface Todo {
title: string;
description: string;
completed: boolean;
}
type TodoPreview = Omit<Todo, 'description'>;
const todo: TodoPreview = {
title: 'Clean room',
completed: false,
description: 'description', // Error: 'description' is not assignable to type
};
모든 프로퍼티를 선택한 다음 K를 제거한 타입을 구성한다.
6. Exclude<T,U>
type T0 = Exclude<'a' | 'b' | 'c', 'a'>;
// "b" | "c"
type T1 = Exclude<'a' | 'b' | 'c', 'a' | 'b'>;
// "c"
type T2 = Exclude<string | number | (() => void), Function>;
// string | number
T에서 U에 할당할 수 있는 모든 속성을 제외 한 타입을 구성한다.
7. Extract<T,U>
type T0 = Extract<'a' | 'b' | 'c', 'a' | 'f'>;
// "a"
type T1 = Extract<string | number | (() => void), Function>;
// () => void
T에서 U에 할당 할 수 있는 모든 속성을 추출 하여 타입을 구성한다.
8. NonNullable
type T0 = NonNullable<string | number | undefined>;
// string | number
type T1 = NonNullable<string[] | null | undefined>;
// string[]
null 과 undefined를 제외한 타입이다.
9. Parameters
declare function f1(arg: { a: number; b: string }): void;
type T0 = Parameters<() => string>; // []
type T1 = Parameters<(s: string) => void>; // [string]
type T2 = Parameters<<T>(arg: T) => T>; // [unknown]
type T4 = Parameters<typeof f1>; // [{ a: number, b: string }]
type T5 = Parameters<any>; // unknown[]
type T6 = Parameters<never>; // never
type T7 = Parameters<string>; // 오류
type T8 = Parameters<Function>; // 오류
함수 타입 T의 매개변수 타입들의 튜플 타입을 구성한다.
10. ConstructorParameters
type T10 = ConstructorParameters<ErrorConstructor>; // [(string | undefined)?]
type T1 = ConstructorParameters<FunctionConstructor>; // string[]
type T2 = ConstructorParameters<RegExpConstructor>; // [string, (string | undefined)?]
interface I1 {
new (args: string): Function;
}
type T12 = ConstructorParameters<I1>; // [string]
function f1(a: T12) {
a[0];
a[1]; // Error: Tuple type '[args: string]' of length '1' has no element at index '1'.
}
생성자 함수 타입의 모든 매개변수 타입을 추출한다.
모든 매개변수 타입을 가지는 튜플 타입(T가 함수가 아닌 경우 never)을 생성한다.
11. ReturnType
declare function f1(): { a: number; b: string };
type T0 = ReturnType<() => string>; // string
type T1 = ReturnType<(s: string) => void>; // void
type T2 = ReturnType<<T>() => T>; // {}
type T3 = ReturnType<<T extends U, U extends number[]>() => T>; // number[]
type T4 = ReturnType<typeof f1>; // { a: number,b: string }
type T5 = ReturnType<any>; // any
type T6 = ReturnType<never>; // any
type T7 = ReturnType<string>; // 오류
type T8 = ReturnType<Function>; // 오류
함수 T의 반환 타입으로 구성된 타입을 생성한다.
12. Required
interface Props {
a?: number;
b?: string;
}
const obj: Props = { a: 5 };
const obj2: Required<Props> = { a: 5 };
// Error: Property 'b' is missing in type '{ a:number; }
T의 모든 프로퍼티가 필수로 설정된 타입을 구성한다.