Ch.Covelope

[Typescript] - Exclude, Omit, Pick, Partial, Required, Record / 유틸리티 타입(Utility types) 본문

TypeScript

[Typescript] - Exclude, Omit, Pick, Partial, Required, Record / 유틸리티 타입(Utility types)

Chrysans 2023. 9. 21. 15:32
반응형
728x90

 

반응형

 

 

 

 


 

 

 

타입스크립트 이미지

 

 


 

 

유틸리티 타입(Utility type)이란?

TypeScript에서 제공하는 내장 타입 중 하나로, 기존 타입을 조작하고 변환하는 데 사용되는 타입이다. 이러한 유틸리티 타입은 코드를 더 간결하고 유지보수하기 쉽게 만들어주며, 타입 안정성을 높이는 데 도움이 된다.

 

 

자주 사용되는 TypeScript 유틸리티 타입들

 

Exclude<UnionType, ExcludedMembers>

ExcludedMembers'에 할당할 수 있는 모든 union 멤버를 'UnionType'에서 제외하여 Type을 생성합니다.
type T0 = Exclude<"a" | "b" | "c", "a">;    
     //type T0 = "b" | "c"
     
type T1 = Exclude<"a" | "b" | "c", "a" | "b">;
     //type T1 = "c"
     
type T2 = Exclude<string | number | (() => void), Function>;
     //type T2 = string | number

 

UnionType 에 'a' | 'b' | 'c'  가 있을때 ExcludedMembers 에 제외하고 싶은 타입을 넣어주면 해당 타입이 제외된 나머지 타입이 생성된다.

 

type Food = '야채' | '고기' | '생선';

// 나는 고기를 좋아해

type FavoriteFood = Exclude<Food, '야채' | '생선'>
// type FavoriteFood = '고기'

또는

interface Food {
  set1: '야채세트',
  set2: '생선세트',
  set3: '한우세트'
}

type FavoriteFood = Exclude<keyof Food, 'set1' | 'set2'>
// type FavoriteFood = 'set3' = '한우세트'

 

 


 

 

Omit<Type, Keys>

Omit 은 어떤 정의된 객체 형태의 타입에서 특정한 프로퍼티들을 제외.
interface Todo {
  title: string;
  description: string;
  completed: boolean;
  createdAt: number;
}
 
type TodoPreview = Omit<Todo, "description">;

// description 제외

type TodoPreview = {
    title: string;
    completed: boolean;
    createdAt: number;
}

 

interface Todo 가 가진 타입에서 description 을 제외한 나머지 타입을 만들어 준다.

 

Omit은 기존에 interface 등으로 정의한 타입에서, 특정한 프로퍼티들만 제외하고 재활용하고 싶을 때 사용 할 수 있다. 

 

 


 

 

Pick<Type, Keys>

Pick 은 정의된 객체 형태의 타입에서 특정한 프로퍼티를 골라서 새로운 타입으로 만든다.

 

interface Todo {
  하지마: string;
  나픽: string;
  나도픽: boolean;
}
 
type TodoPreview = Pick<Todo, "나픽" | "나도픽">;
 
const todo: TodoPreview = {
  나픽: "pick",
  나도픽: "pickToo",
};

타입 이름과 같이 Pick은 픽한 프로퍼티로 새로운 타입을 만든다.

 

 


 

Partial<Type>

Patial은 주어진 타입의 모든 속성을 선택적(옵셔널) 으로 만들어 준다.
interface Todo {
  title: string,
  subTitle: string,
  content: string,
  subContent: string
}


function updateTodo(todo: Todo, fieldsToUpdate: Todo) {
  return { ...todo, ...fieldsToUpdate };
}

updateTodo(todo, {title: 'mondayDo'})

 //Type '{ title: string; }' is missing the following properties from type 'Todo': subTitle, content, subContentts(2345)

 

기존 todo 에서 title만 새로 업데이트 하고 싶은데 기존 타입이 전부 필수여서 에러가 발생

 

interface Todo {
  title: string,
  subTitle: string,
  content: string,
  subContent: string
}


function updateTodo(todo: Todo, fieldsToUpdate: Partial<Todo>) {
  return { ...todo, ...fieldsToUpdate };
}

updateTodo(todo, {title: 'mondayDo'})
// 성공

Partial 됬을때에 Todo interface의 모습

interface Todo {
  title?: string,
  subTitle?: string,
  content?: string,
  subContent?: string
}

type에 직접 optional로 넣지 않고 필요에 따라 선택적으로 optional하게 타입을 사용할수 있다.

 

 


 

Required<Type>

Partial 과 반대로 모든 프로퍼티를 필수(required)로 바꿔 준다. (optional 제거)
 // a , b = optional
interface Props {
  a?: number;
  b?: string;
}
 
const obj: Props = { a: 5 };
 
//Required 사용시 Props의 값이들 필수값으로
const obj2: Required<Props> = { a: 5 };

//필수 값이 없기 떄문에 에러 발생
Property 'b' is missing in type '{ a: number; }' but required in type 'Required<Props>'.

 

 


 

Record<Keys,Type>

Record 를 사용하여 키와 값의 타입을 지정한 객체를 생성할 수 있다.
interface StudentInfo {
  age: number;
  dream: string;
}
 
type StudentName = "terry" | "teddy" | "tom"; // 셋 중 하나라도 빠지면 에러
 
const student: Record<StudentName, StudentInfo> = {
  terry: { age: 10, dream: "대통령" },
  teddy: { age: 5, dream: "ufc챔피언" },
  tom: { age: 16, dream: "부자" },
};

// 키에는 StudentName 타입만 가능하고 , value에는 StudentInfo 타입만 가능하다.


Record<string, number>
// 키에는 string 타입만, value에는 number 타입만 가능하다

const grade : Record<string, number> = {
 tom: 10,
 terry: 4,
 john: 2
}

 

Record는 객체의 타입을 정의하는 특징을 바탕으로 유용하가 사용할수 있다.

 

 


 

 

ReturnType<Type>

함수T의 반환 타입은 함수가 실행된 후에 어떤 종류의 값이 반환되는지를 나타낸다.
예를 들어, 함수가 숫자를 반환하면 반환 타입은 number 이며,
함수가 문자열을 반환하면 반환 타입은 string 이다.
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

 

 ReturnType 은 함수가 반환하는 타입을 타입으로 사용한다

 

ReturnType<void>
 모든 함수의 반환 타입을 void 로 간주하지만,

ReturnType<never>
 어떤 함수도 반환하지 않음을 나타낸다.

ReturnType<any>
어떤 함수도 any 타입으로 간주

 

 


 

 

https://covelope.tistory.com/

 

Ch.Covelope

Chrys_Code_Develope. https://velog.io/@goggg8822

covelope.tistory.com

 

 

 


 

728x90
반응형

'TypeScript' 카테고리의 다른 글

typeScript (타입스크립트) 시작하기  (0) 2022.04.18
Comments