Language/Typescript

utility 타입

kimjingyu 2023. 5. 13. 20:57
728x90

예시 interface

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

1. Partial 타입

  • interface 내 변수를 모두 ?: 로 바꾼다.
type a = Partial<IProfile>

2. Required 타입

  • interface 내 변수를 모두 : 로 바꾼다.
type b = Required<IProfile>

3. Pick 타입

  • interface 내 변수 중 원하는 변수를 골라서 객체를 만든다.
type c = Pick<IProfile, "name" | "age">

4. Omit 타입

  • interface 내 변수 중 원하는 변수를 제외하고 객체를 만든다.
type d = Omit<IProfile, "school">

5. Record 타입

type e = "철수" | "영희" | "훈이"   // Union 타입
let child1: e = "영희"  // 철수, 영희, 훈이만 된다.
let child2: string = "사과"

type f = Record<e, IProfile>    // Record 타입

// type f = {
//     철수: IProfile;
//     영희: IProfile;
//     훈이: IProfile;
// }

6.  keyof

  • interface 내 변수 중에서 key만 뽑아낸다.
  • 이 객체의 key들로 Union 타입을 만든다.
type g = keyof IProfile
let myProfile: g = "name"

7. type vs interface의 차이

  • interface는 선언병합이 가능하다.
  • type으로 만든 것들은 선언병합이 불가능하다.
export interface IProfile {
    candy: number   // 선언병합으로 추가
}

8. 배운 것 응용

  • IProfile interface 내 모든 변수를 ?: 로 바꾸고, 여기에 candy를 선언병합으로 추가
let profile: Partial<IProfile> = {
    candy: 10
}
728x90