• Home
  • About
    • lahuman photo

      lahuman

      열심히 사는 아저씨

    • Learn More
    • Facebook
    • LinkedIn
    • Github
  • Posts
    • All Posts
    • All Tags
  • Projects

Typescript에서 특정 key를 가진 타입 생성

24 Aug 2023

Reading time ~2 minutes

Typescript에서 특정 key를 가진 타입 생성

약속된 키만 가진 클래스를 생성하려다 실패했습니다. 검색을 해보니, Type이나, Record를 사용하라고 되어 있네요.

type을 이용한 처리

type DayOfTheWeek = "sunday" | "monday" | "tuesday" | "wednesday" | "thursday" | "friday" | "saturday";

type ChoresMap = { [DAY in DayOfTheWeek]: string };

const chores: ChoresMap = { // ERROR! Property 'saturday' is missing in type '...'
    "sunday": "do the dishes",
    "monday": "walk the dog",
    "tuesday": "water the plants",
    "wednesday": "take out the trash",
    "thursday": "clean your room",
    "friday": "mow the lawn",
};

Record 를 이용한 처리

Record는 프로퍼티 키가 Keys이고 프로퍼티 값이 Type인 객체 유형을 생성합니다. 이 유틸리티는 타입의 프로퍼티를 다른 타입에 매핑하는 데 사용할 수 있습니다.

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

옵션 key 처리

Record은 key를 필수 값으로 만듭니다.

이를 옵션으로 처리 하기 위해서는 Partial을 이용합니다.

코드는 아래와 같습니다.

// type
type DayOfTheWeek = "sunday" | "monday" | "tuesday" | "wednesday" | "thursday" | "friday" | "saturday";

type ChoresMap = { [DAY in DayOfTheWeek]: string };

const chores: Partial<ChoresMap> = { // Partial 을 이용한 옵션 처리
    "sunday": "do the dishes",
    "monday": "walk the dog",
};

// 동료가 주신 다른 방법 
type DayOfTheWeek = "sunday" | "monday" | "tuesday" | "wednesday" | "thursday" | "friday" | "saturday";

type ChoresMap = { [DAY in DayOfTheWeek]?: string }; // ? 를 이용하여 옵션으로 변경

const chores: ChoresMap = { 
    "sunday": "do the dishes",
};

// Record
interface CatInfo {
  age: number;
  breed: string;
}
 
type CatName = "miffy" | "boris" | "mordred";
 
const cats: Partial<Record<CatName, CatInfo>> = { // Partial 을 이용한 옵션 처리
  miffy: { age: 10, breed: "Persian" },
  boris: { age: 5, breed: "Maine Coon" },
};

참고자료

  • Enforcing the type of the indexed members of a Typescript object?
  • Define a list of optional keys for Typescript Record


typescripttyperecord Share Tweet +1