본문 바로가기
Typescript

Typescript Utility Types 정리

by 도현위키 2022. 4. 20.

들어가며

매번 Utility Types 관련해서 한 번 정리하려고 마음만 먹고 미뤘다가 드디어 오늘 정리 해보려고 한다. 더 자세한 내용을 보려면 공식문서를 참고하면 된다

 

 

Partial<Type>

Partial은 Type의 들어가는 속성들을 전부 optional type으로 셋팅하고 반환한다.

 

interface User {
    email: string;
    name: string;
}

type User2 = Partial<User> 

/*
User2의 타입은 { 
    email?: string | undefined;
    name?: string | undefined;
}
* 
*/

 

Required<Type>

Required는 Type의 들어가는 속성들을 전부 필수 type으로 세팅하고 반환한다. Partial<Type>의 반대 효과이다.

 

interface User {
    email?: string | undefined;
    name?: string | undefined;
}

type User2 = Required<User>

/*
User2의 타입은 { 
    email: string;
    name: string;
}
* 
*/

 

 

Readonly<Type>

Readonly Type의 들어가는 속성들은 전부 읽기 전용(readonly)로 세팅하고 반환된다. 즉 반환된 타입의 프로퍼티는 재할당될 수 없다.

 

interface Post {
  title: string;
}

const post: Post = {
  title: "first title"
}

// 일반 Post 타입은 title을 재할당 할 수 있다.
post.title = "second title"


// Readonly 타입은 재할당이 불가능하다.
const newPost: Readonly<Post> = {
  title: "first title"
}

newPost.title = "second title" // 오류 Cannot assign to 'title' because it is a read-only property.

 

 

Record<Keys, Type>

Type의 프로퍼티를 다른 타입의 Key 값에 매핑시킨다.

 

interface Post {
  title: string;
}

type PostInfo = "notice" | "about"

const post: Record<PostInfo, Post> = {
  notice: { title: "공지사항" },
  about: { title: "about~" },
}

 

 

Pick<Type, Keys>

Type의 프로퍼티중 Keys의 집합들 선택해 타입을 생성한다.

 

interface Post {
  title: string;
  description: string;
  writer: string;
}

type PostDetail = Pick<Post, "title" | "description">;

const post: PostDetail = {
  title: "게시물",
  description: "내용"
}

 

 

Omit<Type, Keys>

Type의 프로퍼티중 Keys를 제거한 타입을 생성한다.

 

interface Post {
  id: number;
  title: string;
  description: string;
  writer: string
}

type PostWriter = Omit<Post, "title" | "description">

const postWriter: PostWriter = {
  id: 1,
  writer: "도현"
}

 

 

Exclude<Type, ExcludeUnion>

Type중에서 ExcludeUnion이 해당하는 타입을 제외하여 타입을 생성한다.

 

type Color = "white" | "yellow" | "pink" | "black"

type BrightColor = Exclude<Color, "black">

// type BrightColor = "white" | "yellow" | "pink"

 

 

Extract<Type, Union>

Type중에서 Union이 해당하는 타입을 가져와서 타입을 생성한다.

 

type Color = "white" | "yellow" | "brown" | "black";

type DarkColor = Extract<Color, "black" | "brown" | "blue">;

// type DarkColor = "brown" | "black"

 

 

NonNullable<Type>

Type에서 null과 undefined를 제외하고 타입을 생성한다.

 

type FolderId = NonNullable<string | number | undefined>
// type FolderId = string | number

type BookmarkList = NonNullable<string[] | null | undefined>
// type BookmarkList = string[]

 

 

Parameters<Type>

함수 Type의 매개변수에 사용된 타입으로 튜플 타입을 생성한다.

 

declare function f1(arg: { a: number; b: string }): void;

type T0 = Parameters<() => string>;
// type T0 = []

type T1 = Parameters<(s: string) => void>;
// type T1 = [s: string]

type T2 = Parameters<<T>(arg: T) => T>;
// type T2 = [arg: unknown]

type T3 = Parameters<typeof f1>;
/* 
type T3 = [arg: {
    a: number;
    b: string;
}]
*/

type T4 = Parameters<any>;
// type T4 = unknown[]

type T5 = Parameters<never>;
// type T5 = never

type T6 = Parameters<string>;
// Error: Type 'string' does not satisfy the constraint '(...args: any) => any'.

type T7 = Parameters<Function>;
// Error: Type 'Function' does not satisfy the constraint '(...args: any) => any'.
//  Type 'Function' provides no match for the signature '(...args: any): any'.

 

 

ReturnType<Type>

함수 Type의 반환 타입으로 구성된 타입을 생성한다.

 

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>; // Error
type T8 = ReturnType<Function>; // Error

 

 

InstanceType<Type>

Type의 생성자 함수의 인스턴스 타입으로 구성된 타입을 생성한다.

 

class C {
  x = 0;
  y = 0;
}

type T0 = InstanceType<typeof C>; // C
type T1 = InstanceType<any>; // any
type T2 = InstanceType<never>; // any
type T3 = InstanceType<string>; // Error
type T4 = InstanceType<Function>; // Error

 

댓글