#TypeScript (6) Utility Type 2
유틸리티 타입
TypeScript는 일반적인 타입 변환을 쉽게 하기 위해서 몇 가지 유틸리티 타입을 제공합니다. 이러한 유틸리티는 전역으로 사용 가능합니다.
Pick<Type, Keys>
Type에서 프로퍼티 Keys의 집합을 선택해 타입을 생성합니다. Omit의 반대라고 생각하면 편합니다.
interface BookInfo {
title: string
theme: string
publication: number
}
type BookInfoPick = Pick<BookInfo, "title" | "theme">
const person: BookInfoPick = {
title: "COSMOS",
theme: "Cosmology"
}
// 타입의 원하는 키 프로퍼티를 선택합니다.
TS Playground - An online editor for exploring TypeScript and JavaScript
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
www.typescriptlang.org
Exclude<Type, ExcludedUnion>
ExcludedUnion에 할당할 수 있는 모든 유니온 멤버를 Type에서 제외하여 타입을 생성합니다.
type Ex0 = Exclude<"a" | "b" | "c" , "a" | "b"> // "c"만 키의 프로퍼티로 타입 사용
type Animal = "Man" | "Woman" | "Bird" | "Fox"
type PersonEx1 = Exclude<Animal, "Bird" | "Fox"> // "Man"과 "Woman"만 키의 프로퍼티로 타입 사용
type AnimalEx2 = Exclude<Animal, "Man" | "Woman"> // "Bird"와 "Fox"만 키의 프로퍼티로 타입 사용
type Ex3 = Exclude<string | number | boolean | undefined, string | boolean> // number와 undefined만 키의 프로터피로 타입 사용
TS Playground - An online editor for exploring TypeScript and JavaScript
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
www.typescriptlang.org
Extract<Type, Union>
Union에 할당할 수 있는 모든 유니온 멤버를 Type에서 가져와서 타입을 생성합니다. 간단하게 교집합이라 생각하면 됩니다.
type Ex0 = Extract<"a" | "b" | "c", "b" | "k">
type Ex1 = Extract<number | string | "a", "a" | Function> // 타입의 키를 가진 프로퍼티 사이에 그냥 키가 겹쳐도 never가 나옴
type Ex2 = Extract<undefined | boolean | (() => void), Function | void> // 함수의 키를 가진 프로퍼티인 () => void가 나옴
TS Playground - An online editor for exploring TypeScript and JavaScript
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
www.typescriptlang.org
NonNullable<Type>
Type에서 null과 정의되지 않은 것(undefined)을 제외하고 타입을 생성합니다.
type Ex0 = NonNullable<string | number | null> // string, number
type Ex1 = NonNullable<never | string | 0> // string, 0
type Ex2 = NonNullable<undefined | {}> // empty
type Ex3 = NonNullable<{name: string, age: undefined} | (() => null)> // {}안에 키 타입 프로퍼티와 함수의 프로퍼티가 같이 사용 가능
TS Playground - An online editor for exploring TypeScript and JavaScript
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
www.typescriptlang.org
정리
- 유틸리티 타입을 통해 다양하게 타입을 사용할 수 있음
- 아직 예시만 봐와서 언제 어떻게 어디에서 사용하는지는 잘 모르겠네요...
https://www.typescriptlang.org/ko/docs/handbook/utility-types.html
Documentation - Utility Types
Types which are globally included in TypeScript
www.typescriptlang.org