더북(TheBook)

따라서 인덱스 시그니처를 사용해 다음과 같이 타이핑할 수 있습니다. 이렇게 하면 sirius의 오타는 잡힙니다.

const universe: { 
  [key in 'sun' | 'sirius' | 'earth']: { type: string, parent: string } | string
} = {
  sun: "star",
  sriius: "star", // sirius 오타
  earth: { type: "planet", parent: "sun" },
};
// Type '{ sun: string; sriius: string; earth: { type: string; parent: string; }; }' is not assignable to type '{ sun: string | { type: string; parent: string; }; sirius: string | { type: string; parent: string; }; earth: string | { type: string; parent: string; }; }'. Object literal may only specify known properties, but 'sriius' does not exist in type '{ sun: string | { type: string; parent: string; }; sirius: string | { type: string; parent: string; }; earth: string | { type: string; parent: string; }; }'. Did you mean to write 'sirius'?

다만 속성 값을 사용할 때가 문제입니다. earth의 타입이 객체라는 것을 제대로 잡아내지 못합니다.

universe.earth.type;
// Property 'type' does not exist on type 'string | { type: string; parent: string; }'. Property 'type' does not exist on type 'string'.
신간 소식 구독하기
뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.