개발자 박가나
[241206 TIL] 본캠프 48일차 (Generic과 Utility Type) 본문
Generic
클래스나 함수 등에서 타입을 마치 파라미터처럼 사용하는 것을 의미한다.
아래 코드의 경우, 두 함수의 로직은 동일하지만 각각 string과 number 타입만 처리할 수 있기 때문에 중복 코드가 발생하게 된다.
function printStrings(arr: string[]): void {
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
}
function printNumbers(arr: number[]): void {
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
}
printStrings(['a', 'b', 'c']);
printNumbers([1, 2, 3]);
이러한 경우, 아래 코드처럼 Generic을 사용해서 여러 타입을 처리할 수 있다.
function printAnything<T>(arr: T[]): void {
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
}
printAnything(['a', 'b', 'c']);
printAnything([1, 2, 3]);
Utility Type
타입 변환을 용이하게 하기 위해서 TypeScript에서 지원하는 문법이다.
Pick<T, K>
T에서 프로퍼티 K의 집합을 선택해서 타입을 구성한다.
interface Todo {
title: string;
description: string;
completed: boolean;
}
type PickTodo = Pick<Todo, 'title' | 'completed'>;
// { title: string; completed: boolean; }
Omit<T, K>
T에서 프로퍼티 K를 제거해서 타입을 구성한다.
interface Todo {
title: string;
description: string;
completed: boolean;
}
type OmitTodo = Omit<Todo, 'description'>;
// { title: string; completed: boolean; }
Exclude<T, U>
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
Partial<T>
T의 모든 프로퍼티를 선택적으로 만들어서 타입을 구성한다.
interface Todo {
title: string;
description: string;
}
type PartialTodo = Partial<Todo>;
// { title?: string; description?: string; }
ReadOnly<T>
T의 모든 프로퍼티를 읽기 전용으로 만들어서 타입을 구성한다.
interface Todo {
title: string;
}
const todo: Readonly<Todo> = {
title: 'Delete inactive users',
};
todo.title = 'Hello'; // 오류: 읽기 전용 프로퍼티에 재할당할 수 없음
Record<K, T>
타입 T의 프로퍼티의 집합 K로 타입을 구성한다.
interface PageInfo {
title: string;
}
type Page = 'home' | 'about' | 'contact';
const x: Record<Page, PageInfo> = {
about: { title: 'about' },
contact: { title: 'contact' },
home: { title: 'home' },
};
Extract<T, U>
T에서 U에 할당할 수 있는 모든 속성을 추출해서 타입을 구성한다.
type T0 = Extract<"a" | "b" | "c", "a" | "f">; // "a"
type T1 = Extract<string | number | (() => void), Function>; // () => void
ReturnType<T>
T 함수의 반환 값으로 타입을 구성한다.
function getUser() {
return { name: 'Alice', age: 25 };
}
type User = ReturnType<typeof getUser>;
const user: User = { name: 'Alice', age: 25 };
Parameters<T>
T 함수의 매개변수 타입을 튜플로 만들어서 타입을 구성한다.
function log(message: string, userId: number): void {
console.log(`${userId}: ${message}`);
}
type LogParams = Parameters<typeof log>;
const params: LogParams = ['Hello, world!', 1];
log(...params); // 1: Hello, world!
Awaited<T>
Promise의 결과 타입을 추론해서 타입을 구성한다.
async function fetchData(): Promise<string> {
return "Hello, world!";
}
// fetchData 함수의 반환 타입 추론
type FetchDataType = Awaited<ReturnType<typeof fetchData>>;
const data: FetchDataType = await fetchData();
console.log(data); // "Hello, world!"
'내일배움캠프' 카테고리의 다른 글
[241210 TIL] 본캠프 50일차 (Caching) (0) | 2024.12.10 |
---|---|
[241209 TIL] 본캠프 49일차 (Next.js의 렌더링 기법 4가지) (4) | 2024.12.09 |
[241205 TIL] 본캠프 47일차 (아웃소싱 프로젝트 회고) (0) | 2024.12.05 |
[241202 TIL] 본캠프 44일차 (Funnel 패턴) (0) | 2024.12.02 |
[241129 TIL] 본캠프 43일차 (useInfiniteQuery) (0) | 2024.11.29 |