TypeScript

[TypeScript] 유틸리티 타입

머지?는 병합입니다 2024. 12. 22. 01:36

1. Partial<Type>
타입의 모든 속성을 선택적(optional)으로 만듭니다.

interface Todo {
  title: string;
  description: string;
}

// 모든 필드가 선택적이 됨
type PartialTodo = Partial<Todo>; // { title?: string; description?: string; }


const aa: Todo = {}; // 가능
const bb: Todo = { title: 'title' }; // 가능
const cc: Todo = { description: 'description' };  // 가능
const dd: Todo = { title: 'title', description: 'description' }; // 가능

 

2. Required<Type>
Partial의 반대로, 모든 속성을 필수로 만듭니다.

 

3. Pick<Type, Keys>
특정 타입에서 몇 개의 속성을 선택하여 타입을 구성합니다.

interface Todo {
  title: string;
  description: string;
  completed: boolean;
}

type TodoPreview = Pick<Todo, "title" | "completed">;

 

4. Omit<Type, Keys>
특정 속성만 제외한 타입을 구성합니다.

interface Todo {
  title: string;
  description: string;
  completed: boolean;
  createdAt: number;
}
 
type TodoPreview = Omit<Todo, "description">;
 
const todo: TodoPreview = {
  title: "Clean room",
  completed: false,
  createdAt: 1615544252770,
};
 
 
 type TodoInfo = Omit<Todo, "completed" | "createdAt">;
 
const todoInfo: TodoInfo = {
  title: "Pick up kids",
  description: "Kindergarten closes at 5pm",
};

 

5. Record<keys, type></keys, type>
키-값 쌍의 타입을 만듭니다

type CatName = "miffy" | "boris" | "mordred";
 
interface CatInfo {
  age: number;
  breed: string;
}
 
const cats: Record<CatName, CatInfo> = {
  miffy: { age: 10, breed: "Persian" },
  boris: { age: 5, breed: "Maine Coon" },
  mordred: { age: 16, breed: "British Shorthair" },
};
 
cats.boris;

 

6. Awaited<Type>

Promise의 반환 타입을 추론하는데 사용됩니다.

// 1. 기본적인 Promise 타입 추론
type A = Awaited<Promise<string>>;  
// type A = string

// 2. 중첩된 Promise 처리
type B = Awaited<Promise<Promise<number>>>;  
// type B = number

// 3. 유니온 타입에서의 사용
type C = Awaited<boolean | Promise<number>>;
// type C = boolean | number

// 4. 실제 사용 예시
async function fetchUser() {
    return { id: 1, name: "Kim" };
}

type UserType = Awaited<ReturnType<typeof fetchUser>>;
// type UserType = { id: number; name: string; }

 

 

기타 속성들..


Readonly
모든 속성을 읽기 전용으로 만듭니다.

 


Exclude<Type, ExcludedUnion>
유니온 타입에서 특정 타입을 제외합니다.


Extract<Type, Union>
유니온 타입에서 특정 타입만 추출합니다.


NonNullable<Type>
null과 undefined를 제외한 타입을 구성합니다.


ReturnType<Type>
함수의 반환 타입을 추출합니다.

https://daunje0.tistory.com/321

 

[TypeScript] 유틸리티 타입 - ReturnType 가이드

TypeScript를 사용하다 보면 함수의 반환 타입을 활용해야 할 때가 많습니다. 이럴 때마다 매번 타입을 정의하는 것은 번거롭고, 코드 유지보수에도 좋지 않죠. TypeScript의 내장 유틸리티 타입인 Retu

daunje0.tistory.com

 


Parameters<Type>
함수의 매개변수 타입을 튜플 타입으로 추출합니다.


InstanceType<Type>
생성자 함수의 인스턴스 타입을 구성합니다.