[TypeScript] Union Type & Intersection Types


1. Union Type : μ—¬λŸ¬ νƒ€μž… 쀑 ν•˜λ‚˜λ₯Ό λ§Œμ‘±ν•˜λŠ” ν•˜λ‚˜μ˜ νƒ€μž… (ORμ—°μ‚°μž)

  • λ³€μˆ˜μ˜ 값이 μ—¬λŸ¬ νƒ€μž…μ„ κ°€μ§€λŠ” 경우 주둜 μ‚¬μš© (κ°€μž₯ 많이 μ“°μž„)
type Direction = "left" | "right" | "up" | "down";

function move(direction: Direction) {
  console.log(direction);
}
move("down"); // κ°’: down

6. Intersection Types : μ—¬λŸ¬ νƒ€μž…μ„ λͺ¨λ‘ λ§Œμ‘±ν•˜λŠ” ν•˜λ‚˜μ˜ νƒ€μž… (ANDμ—°μ‚°μž)

type Student = {
  name: string;
  score: number;
};

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

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

interWork({
  name: "kdn",
  score: 1,
  empoyeeId: 123,
  work: () => {},
});