나 개발자 할래요
2024.10.01 본문
제네릭
타입을 마치 클래스나 함수 등에서 파라미터처럼 사용하는 것
function printAnything<T>(arr: T[]): void {
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
}
printAnything(['a', 'b', 'c']); // <string>을 써주지 않아도 타입 추론이 가능
printAnything([1, 2, 3]); // <number>를 써주지 않아도 타입 추론이 가능
React Hooks에서도 Generic을 사용할 수 있습니다.
import { useState } from "react";
function App() {
const [counter, setCounter] = useState<number>(1);
const increment = () => {
setCounter((prev) => prev++);
};
return <div onClick={increment}>{counter}</div>;
}
export default App;
useState 뒤에 <>와 number 타입을 넣어주면 counter 와 setCounter 에 각각 number, number 를 인자로 받는 함수의 타입이 할당됩니다.
제네릭을 사용하지 않고 초깃값을 설정을 통해 타입 추론을 할 수 있습니다.
실전 유틸리티 타입
유틸리티 타입
: 타입을 통해 간단한 계산을 수행해 주는 타입 (타입 변환을 용이하게 하기 위해서 TS에서 지원하는 문)
Pick<T, K>
T에서 프로퍼티 K의 집합을 선택해 타입을 구성합니다.
interface Todo {
title: string;
description: string;
completed: boolean;
}
type TodoPreview = Pick<Todo, 'title' | 'completed'>;
const todo: TodoPreview = {
title: 'Clean room',
completed: false,
};
Omit<T, K>
T에서 모든 프로퍼티를 선택한 다음 K를 제거한 타입을 구성합니다.
interface Todo {
title: string;
description: string;
completed: boolean;
}
type TodoPreview = Omit<Todo, 'description'>;
const todo: TodoPreview = {
title: 'Clean room',
completed: false,
};
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;
}
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',
});
console.log(todo1) //{ title: 'organize desk', description: 'clear clutter' }
console.log(todo2) //{ title: 'organize desk', description: 'throw out trash' }
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의 결과 타입을 추론합니다. 비동기 함수의 반환 타입을 처리하거나, 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!"
'개발자 되는 법... > TIL...' 카테고리의 다른 글
2024.10.02 (3) | 2024.10.02 |
---|---|
2024.10.01 (1) | 2024.10.01 |
2024.09.30 (1) | 2024.10.01 |
2024.09.30 (1) | 2024.09.30 |
2024.09.30 (1) | 2024.09.30 |