FrontEnd/ES&JS 문법

[Typescript] Utility Type 정리(ReturnType, Required 등)

기은P 2022. 11. 3. 09:57
반응형

1. Partial<Type>

Type 집합의 모든 프로퍼티를 선택적으로 타입을 생성해줍니다. 그리고 이 유틸리티는 특정 타입의 부분 집합을 만족하는 타입을 정의할 수 있습니다.

interface Address {
  email: string;
  address: string;
}

type MyEmail = Partial<Address>;
const me: MyEmail = {}; // 가능
const you: MyEmail = { email: "noh5524@gmail.com" }; // 가능
const all: MyEmail = { email: "noh5524@gmail.com", address: "secho" }; // 가능

interface Product {
  id: number;
  name: string;
  price: number;
  brand: string;
  stock: number;
}

// Partial - 상품의 정보를 업데이트 (put) 함수 -> id, name 등등 어떤 것이든 인자로 들어올수있습니다
// 현재 Product type은 인자에 type으로 Product를 넣으면 모든 정보를 다 넣어야하는데, 사실
// 아래와 같이 인터페이스를 정의하면 부분적인 데이터만 넣어도 정상적으로 작동합니다.
interface UpdateProduct {
  id?: number;
  name?: string;
  price?: number;
  brand?: string;
  stock?: number;
}
// 그러나 같은 인터페이스를 또 정의하는 것은 비용이 발생하기 때문에
// 이것을 피하기 위해서 Partial을 활용합니다.
function updateProductItem(prodictItem: Partial<Product>) {
  // Partial<Product>이 타입은 UpdateProduct 타입과 동일하다
}

 

 

2. Required<Type>

Required는 Partial과 반대로 모든 프로퍼티를 필수로 설정한 타입을 생성합니다.

interface Props {
  a?: number;
  b?: string;
}
 
const obj: Props = { a: 5 };
 
const obj2: Required<Props> = { a: 5 };

 

 

 

 

3. Pick<Type, Keys>

Pick 타입은 특정 타입에서 Keys라는 몇 개의 속성을 자유롭게 선택(title, completed)해 타입을 반환합니다.

interface Todo {
  title: string;
  description: string;
  completed: boolean;
}
 
type TodoPreview = Pick<Todo, "title" | "completed">;
 
const todo: TodoPreview = {
  title: "Clean room",
  completed: false,
};
console.log(todo)

 

 

 

 

4. Omit<Type, Keys>

Omit 타입은 Pick과 반대로 모든 프로퍼티를 선택한 상태에서 특정 Key를 제외한 타입을 반환합니다.

interface Todo {
  title: string;
  description: string;
  completed: boolean;
}
 
type TodoPreview = Omit<Todo, "description">;
 
const todo: TodoPreview = {
  title: "Clean room",
  completed: false,
};

 

 

 

 

5. Readonly<Type>

Type 집합의 모든 프로퍼티를 읽기 전용으로 설정한 타입을 생성합니다. 이렇게 될 경우 생성된 타입의 프로퍼티는 재할당 될 수 없습니다.

interface Todo {
  title: string;
}
 
const todo: Readonly<Todo> = {
  title: "Delete inactive users",
};
 
 // Cannot assign to 'title' because it is a read-only property.
todo.title = "Hello";

 

 

 

 

6. Record<Keys, Type>

타입 Type의 프로퍼티 의 집합으로 타입을 생성합니다. 이 유틸리티는 타입의 프로퍼티를 다른 타입에 매핑 시키는데 사용될 수 있습니다.

interface PageInfo {
  title: string;
}
 
type Page = "home" | "about" | "contact";
 
const nav: Record<Page, PageInfo> = {
  about: { title: "about" },
  contact: { title: "contact" },
  home: { title: "home" },
};
 
console.log(nav.about);

*Page라는 키에 PageInfo라는 타입을 Record로 연결시켜 각각의 키의 title을 정의하도록 매핑했습니다.

 

 

 

7. ReturnType<Type>

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

declare function f1(): { a: number; b: string };
 
type T0 = ReturnType<() => string>;     
// type T0 = string

type T1 = ReturnType<(s: string) => void>;     
// type T1 = void

type T2 = ReturnType<<T>() => T>;     
// type T2 = unknown

type T3 = ReturnType<<T extends U, U extends number[]>() => T>;     
// type T3 = number[]

type T4 = ReturnType<typeof f1>;     
/*
type T4 = {
    a: number;
    b: string;
}
*/


type T5 = ReturnType<any>;     
//type T5 = any

type T6 = ReturnType<never>;     
//type T6 = never

 

반응형