<TS> 판별 유니온 (discriminated unions)

·2023년 8월 27일
1

TypeScript

목록 보기
6/8

판별 유니온

discriminated unions

모든 타입의 공통된 속성에 판별자를 추가합니다.
사용함으로써 특정 타입의 속성에 접근할 수 있습니다.

interface Rooster {
  name: string;
  weight: number;
  age: number;
  kind: "rooster"; // 판별자는 리터럴 타입이어야 합니다.
}

interface Cow {
  name: string;
  weight: number;
  age: number;
  kind: "cow"; // 판별자
}

interface Pig {
  name: string;
  weight: number;
  age: number;
  kind: "pig"; // 판별자
}

type FarmAnimal = Pig | Rooster | Cow;

function getFarmAnimalSound(animal: FarmAnimal) {
  // 타입에 공통된 속성을 지정하고, switch문으로 판별 가능.
  // if문으로도 당연히 가능합니다.
  switch (animal.kind) {
    case "pig":
      console.log(animal);
      return "돼지를 판별했습니다.";
    case "cow":
      console.log(animal);
      return "소를 판별했습니다.";
    case "rooster":
      console.log(animal);
      return "닭를 판별했습니다.";
    default:
    // 모든 case가 정상적으로 처리되면 default값은 처리되지 않을 것입니다.
  }
}

지정한 타입의 속성을 넣어주면 잘 작동하지만,

지정한 타입의 판별자가 다를 경우 TS에서 에러를 발생시킵니다.

profile
- 배움에는 끝이 없다.

0개의 댓글