[TypeScript] 타입을 조작하는 Utility type 종류, interface와 type의 차이

이주희·2023년 1월 20일
0

TypeScript

목록 보기
10/10
post-thumbnail

Utility type

유틸리티 타입
기존에 있는 타입을 조작해서 쓸 때 사용한다.


예시에 사용할 타입

interface IProfile {
  name: string;
  age: number;
  school: string;
  hobby?: string;
}

1. Partial type

모든 타입이 선택값이 된다.

type IPartialProfile = Partial<IProfile>;

2. Required type

모든 타입이 필수가 된다.

type IRequiredProfile = Required<IProfile>;

3. Pick type

사용할 타입을 지정한다.

type IPickProfile = Pick<IProfile, "name" | "age">;

4. Omit type

지정한 타입을 제외한 타입으로만 이루어진다.

type IOmitProfile = Omit<IProfile, "school">;

5. Record type

객체에서 key에 허용 가능한 값을 제한할 수 있다.

type IUnion = "철수" | "영희" | "훈이"; // Union 타입
type IRecordProfile = Record<IUnion, IProfile>;

6. keyof

key들로 이루어진 Union 타입

type IKeyofProfile = keyof IProfile;
const key: IKeyofProfile = "age";


인터페이스와 타입의 차이

인터페이스는 선언 병합이 가능하다.
👉🏻 인터페이스는 같은 이름으로 또 만들 수 있고, 타입은 또 만들 수 없다!

같은 이름으로 인터페이스를 선언하면 자동으로 합쳐진다.

interface IProfile { 
        name: string
        age: number
        school: string
        hobby?: string
    }
        
//같은 이름의 interface
interface IProfile { 
        candy: number
    }
  
const profile: Partial<IProfile> = {
  name: "주희",
  candy: 1,
};
profile
🍓e-juhee.tistory.com 👈🏻 이사중

0개의 댓글