반응형
1. 개요
Typescript는 가독성과 재사용성을 높이기 위한 utility type들을 제공하고 있다.
utility types는 type의 변경, 새로운 타입의 생성에 유용하게 사용된다.
이번에는 Typescript에서 제공하는 utility type들을 알아보자.
2. 필수 유무 수정(Partial, Required)
Partial<Type>
모든 타입을 optional로 바꾼다.
type Person = { name: string; age: number };
type PartialPerson = Partial<Person>; // { name?: string; age?: number }
Required<Type>
모든 타입을 required로 바꾼다.
type OptionalPerson = { name?: string; age?: number };
type CompletePerson = Required<OptionalPerson>; // { name: string; age: number }
3. 속성 선택, 제거, 변환(Pick, Omit, Readonly)
Pick<Type, Keys>
Keys타입만 선택해 새로운 타입을 만들 수 있다.
type Person = { name: string; age: number; address: string };
type NameAge = Pick<Person, "name" | "age">; // { name: string, age: number; }
Omit<Type, Keys>
Keys타입만 제거해 새로운 타입을 만들 수 있다.
type Person = { name: string; age: number; address: string };
type WithoutAddress = Omit<Person, "address">; // { name: string; age: number }
Readonly<Type>
타입을 읽기전용(readonly)로 변환한다. 생성된 프로퍼티의 타입은 변경할 수 없다.
interface Todo {
title: string;
}
const todo: Readonly<Todo> = {
title: "Delete inactive users",
};
todo.title = "Hello"; // ERROR
4. 속성 변환(Record)
Record<Keys,Type>
객체 타입의 키(Key)와 값(Value) 타입을 지정하여 새로운 타입을 생성한다.
특정 키 목록에 대해 동일한 값 타입을 가지는 객체를 정의할 때 유용하게 사용할 수 있다.
type Role = "admin" | "user" | "guest";
type Permissions = Record<Role, boolean>; // { admin: boolean, user: boolean, guest: boolean }
5. 참고자료
본문에서 다룬것 외의 utility type들은 Typescript 문서에서 확인할 수 있다.
https://www.typescriptlang.org/ko/docs/handbook/utility-types.html
Documentation - Utility Types
Types which are globally included in TypeScript
www.typescriptlang.org
반응형
'프론트엔드' 카테고리의 다른 글
[Frontend] Reflow, Repaint (0) | 2024.11.17 |
---|---|
[React Native] React Native 버전 업그레이드 (2) | 2024.11.16 |
[Javascript] var, let, const의 차이점 (0) | 2024.11.14 |
[Javascript] 호이스팅(Hoisting)은 어떻게 동작하는걸까? (0) | 2024.11.13 |
[React] VitrualDOM을 알아보자! (0) | 2024.11.12 |