728x90
타입스크립트 유틸리티 타입 정리

❓상황

타입스크립트 기본 개념 중 하나인 유틸리티 타입 정리

 

📖 유틸리티 타입이란?

기존의 type alias를 쉽게 변환할 수 있게 도와주는 타입을 뜻한다.

 

쉽게, 하나의 함수라고 생각하면 편하다.

 

🧮 정리

Partial<Type> : Type 타입의 모든 속성이 옵셔널로 변경된 타입을 반환 : 깊은 접근은 안되어 1차 깊이에만 적용된다.

모든 속성을 옵셔널로 바꾸는 것 보단, 일부 속성만 옵셔널로 바꾸는 때가 많아서, Partial 유틸리티 타입은 잘 사용되지 않는다.

type Type = {
	a: string,
	b: string
}

/*
type newType = {
	a?: string | undefined,
	b?: string | undefined
}
*/
type newType = Partial<Type>

 

Required<Type> : Type의 모든 속성에 필수속성으로 변경한 타입을 반환 : 깊은 접근은 안되어 1차 깊이에만 적용된다.

모든 속성을 필수로 바꾸는것 보단, 일부 속성만 필수로 바꾸는 때가 많아서, Required 유틸리티 타입도 잘 사용되지 않는다.

type Type = {
	a?: string,
	b: string
}

/*
type newType = {
	a: string,
	b: string
}
*/
type newType = Required<Type>

 

2차 깊이에도 적용하려면 따로 분리해서 작업을 해야한다.

interface AddressType {
    road_address?: string;
    detail_address: string;
    zipcode: string
}

interface User {
    id: number;
    name?: string;
    username: string;
    phone?: string;
}

/*
interface UserDataType {
  id: number;
  name: string;
  username: string;
  phone: string;
	address: {
    road_address: string;
    detail_address: string;
    zipcode: string
	}
}
*/
type UserDataType = Required<User> & {
    address: AddressType
}

interface UserDataType extends Required<User> {
    address: AddressType
}


const userObj: UserDataType = {
    id: 1,
    name: 'lee',
    username: 'tenenger',
    phone: '010-0000-0000',
    address: {
        road_address: '동대문구',
        detail_address: '103호',
        zipcode: '05321'
    }
}

 

⭐Readonly<Type> : Type 타입의 모든 속성이 readonly로 변경된 타입을 반환 : readonly

개인 프로젝트에는 readonly 속성은 잘 쓰이지 않지만, 규모가 큰 프로젝트를 할때, readonly 속성을 사용한다.

type Type = {
	a: string,
	b: string
}

/*
type newType = {
  readonly a: string;
  readonly b: string;
}
*/
type newType = Readonly<Type>

 

Record<Key, Value> : 속성의 key가 Key이고, 속성의 값은 Value인 타입 반환

만약, Key에 타입(string, number, symbol만 가능)을 넣는다면 index signature와 동일하게 작동한다.

type Type = Record<string, number>

/*
type Type = {
    [x: string]: number;
}
*/

 

Key에 문자열 리터럴 타입도 넣을 수 있다.

type Type = Record<'a' | 'b' | 'c', number>

/*
type Type = {
  a: number,
	b: number,
	c: number	
}
*/

 

⭐⭐Pick<Type, Key> : Type의 Key에 해당되는 부분만 추출하여 새로운 타입으로 반환 : 객체 타입에서 속성을 추출

아주 많이 사용되기 때문에, 기억하고 있으면 좋다.

type Type = {
	a: string,
	b: number,
	c: string.
	d: boolean,
	e: number
}

/*
type NewType = {
	a: string,
}
*/
type NewType = Pick<Type, 'a'>

/*
type NewType = {
	a: string,
	b: number,
	d: boolean,
}
*/
type NewType = Pick<Type, 'a' | 'b' | 'd'>

 

⭐⭐Omit<Type, Key> : Type의 Key에 해당되는 부분만 제외하여 새로운 타입으로 반환 : 객체 타입에서 속성을 제외

아주 많이 사용되기 때문에, 기억하고 있으면 좋다.

type Type = {
	a: string,
	b: number,
	c: string,
	d: boolean,
	e: number
}

/*
type NewType = {
	b: number,
	c: string,
	d: boolean,
	e: number,
}
*/
type NewType = Pick<Type, 'a'>

/*
type NewType = {
	c: string,
	e: number,
}
*/
type NewType = Pick<Type, 'a' | 'b' | 'd'>

 

Exclude<Type, Union> : Type의 Union에 해당되는 부분만 제외하여 새로운 타입으로 반환 : 문자열 리터럴 타입에서 Union를 제외

잘 사용되지는 않아서, 알아만 두자

type Type = 'a' | 'b' | 'c' | 'd';

// type NewType = 'b' | 'c' | 'd';
type NewType = Exclude<Type, 'a'>


type Type = string | number | (() => void);

// type NewType = string | number;
type NewType = Exclude<Type, Function>

 

Extract<Type, Union> : Type의 Union에 해당되는 부분만 추출하여 새로운 타입으로 반환 : 문자열 리터럴 타입에서 Union를 추출잘 사용되지는 않아서, 알아만 두자

잘 사용되지는 않아서, 알아만 두자

type Type = 'a' | 'b' | 'c' | 'd';

// type NewType = 'a';
type NewType = Extract<Type, 'a'>


type Type = string | number | (() => void);

// type NewType = () => void;
type NewType = Extract<Type, Function>

 

NonNullable<Type> : Type에서 null과 undefined를 제외하고 나머지 타입을 반환한다. : 문자열 리터럴 타입에서 null과 undefined를 제외

거의 사용되지는 않아서, 알아만 두자

type Type = string | undefined;

// type NewType = string
type NewType = NonNullable<Type>

 

 

Parameters<FunctionType> : FunctionType의 매개변수에 사용된 타입을 튜플 타입으로 반환

거의 사용되지는 않아서, 알아만 두자

type FunctionType = (name: string, email: string, phoneNumber: number) => void

// type ParameterType = [name: string, email: string, phoneNumber: number]
type ParameterType = Parameters<FunctionType>


function fun (arg: {name: string, email: string, phoneNumber: number}) {}

/*
type ParameterType = [arg: {
    name: string;
    email: string;
    phoneNumber: number;
}]
*/
type ParameterType = Parameters<typeof fun>

 

⭐ReturnType<FunctionType> : FunctionType의 return에 사용된 타입을 반환

자주 사용되는 유틸리티 타입이므로, 외워두도록하자

type FunctionType = (name: string, email: string, phoneNumber: number) => void

// type ParameterType = void
type ParameterType = ReturnType<FunctionType>


function fun (): {name: string, email: string, phoneNumber: number} {}

/*
type ParameterType = {
    name: string;
    email: string;
    phoneNumber: number;
}
*/
type ParameterType = Parameters<typeof fun>
복사했습니다!