[TS] union, intersection

mandarinduk·2021년 3월 17일
0

Union Types

  • OR를 뜻하며, '|' 로 사용
  type Direction = "left" | "right" | "up" | "down";
  function move(direction: Direction) {
    console.log(direction);
  }
  move("left");

  type Size = 8 | 16 | 32;
  const size: Size = 8;
  const size1: Size = 7; // 8, 16, 32만 할당 가능

Intersection Types

  • AND를 뜻하며, '&' 로 사용
  type Student = {
    name: string;
    score: number;
  };

  type Worker = {
    empolyeeId: number;
    work: () => void;
  };

  function interWork(person: Student & Worker) {
    console.log(
      person.name,
      person.empolyeeId,
      person.empolyeeId,
      person.work()
    );
  }

  interWork({
    name: "bae",
    score: 100,
    empolyeeId: 1,
    work: () => {}, // Student와 Worker 타입의 모든 값을 입력하지 않으면 오류 발생!
  });
profile
front-end 신입 개발자

0개의 댓글