교차 타입

여러 타입을 하나로 결합하여 모든 속성을 동시에 포함하는 새로운 타입을 만드는 방식

& 연산자를 사용

type A = { name: string };
type B = { age: number };

type AB = A & B;

const personal : AB = {
  name: "Alice",
  age: 30,
};


주의
교차 타입은 겹치는 속성이 있을 경우 공통적인 타입으로 좁혀짐
호환되지 않는 타입을 결합하면 오류가 발생

ErrorCase

// type C = { value: string };
// type D = { value: number };

// // 오류 발생: string과 number는 교차 불가
// type CD = C & D;

교차 믹스인

교차 타입을 활용해 여러 객체 또는 클래스의 기능을 결합하는 방식

 

 

1. 객체 교차 믹스인
여러 객체를 하나로 병합하는 방식, Object.assign을 활용

type Flyable = { fly: () => void };
type Swimmable = { swim: () => void };

const flyMixin: Flyable = {
  fly: () => console.log("Flying!"),
};

const swimMixin: Swimmable = {
  swim: () => console.log("Swimming!"),
};

// 교차 타입 생성
const flyingFish: Flyable & Swimmable = Object.assign({}, flyMixin, swimMixin);

flyingFish.fly(); // Flying!
flyingFish.swim(); // Swimming!

 

2. 클래스 교차 믹스인
implements와 교차 타입을 활용하여 여러 동작을 클래스에 포함

type Walkable = {
  walk: () => void;
};

type Runnable = {
  run: () => void;
};

class animal implements Walkable, Runnable {
  walk() {
    console.log("Walking!");
  }

  run() {
    console.log("Running!");
  }
}

const dog = new animal();
dog.walk(); // Walking!
dog.run(); // Running!

 

2-1. 믹스인 함수를 사용한 클래스 병합

type CanEat = {
  eat: () => void;
};

type CanSleep = {
  sleep: () => void;
};

function Eater<TBase extends new (...args: any[]) => {}>(Base: TBase) {
  return class extends Base {
    eat() {
      console.log("Eating!");
    }
  };
}

function Sleeper<TBase extends new (...args: any[]) => {}>(Base: TBase) {
  return class extends Base {
    sleep() {
      console.log("Sleeping!");
    }
  };
}

class Personal {}

const MixedPerson = Sleeper(Eater(Personal));

const human = new MixedPerson();
human.eat(); // Eating!
human.sleep(); // Sleeping!

 

'TS' 카테고리의 다른 글

클래스 (2)  (0) 2024.12.03
클래스 (1)  (0) 2024.12.02
리터럴 타입  (0) 2024.11.26
함수(Function)[2]  (0) 2024.11.25
함수(Function)[1]  (0) 2024.11.20

+ Recent posts