프로그래밍 언어/JS TS

TS 클래스 다중 상속하기

트리맨스 2021. 9. 11. 00:30
반응형

 

TS는 기본적으로 클래스 상속을 지원한다. 클래스 상속은 다음과 같이 사용할 수 있다.

 

1
2
3
4
5
6
7
8
9
10
11
12
class A {
  numA: number;
}
 
class B extends A {
  numB: number;
}
 
const newClass = new B();
newClass.numA = 1;
newClass.numB = 2;
 
cs

 

위의 경우에는 클래스 B에서 클래스 A를 상속받아 최종적으로 클래스B에는 numA 와 numB가 모두 들어간 것을 볼 수 있다. 하지만 TS에서는 한 개의 클래스에 대해서는 상속이 가능하나, 여러개의 클래스 상속(다중 상속) 은 안타깝게도 지원하지 않는다. 그렇다면 다중 상속을 사용할 경우에는 어떠한 식으로 접근해야 할까? 답은 mixin을 이용하는 것이다. 함수는 아래 사이트를 참고했다.

 

https://www.typescriptlang.org/docs/handbook/mixins.html

 

Documentation - Mixins

Using the mixin pattern with TypeScript

www.typescriptlang.org

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
 
function applyMixins(outputClass: any, inputClasses: any[]) {
  inputClasses.forEach((inputClass) => {
    Object.getOwnPropertyNames(baseCtor.prototype).forEach((name=> {
      Object.defineProperty(
        derivedCtor.prototype,
        name,
        Object.getOwnPropertyDescriptor(baseCtor.prototypename||
          Object.create(null)
      );
    });
  });
}
 
cs

 

새로 생성할 클래스 output을 정의하고, interface output extends A,B 선언 후 위의 함수를 정의하고 첫번째 입력 변수에 output, 두번째 입력 변수에 [A,B] 를 입력하고 함수를 실행하게 되면 클래스의 다중 상속이 가능해진다. 아래 코드는 사용 예시이다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class One {
  printA() {
    console.log('This class is One');
  }
 
  num1: number;
}
 
class Two {
  printB() {
    console.log('This class is Two');
  }
 
  num2: number;
}
 
class Mixed {
  num3: number;
}
 
interface Mixed extends One, Two {}
 
function applyMixins(outputClass: any, inputClasses: any[]): void {
  inputClasses.forEach((inputClass) => {
    Object.getOwnPropertyNames(inputClass.prototype).forEach((name=> {
      const descriptor = Object.getOwnPropertyDescriptor(
        inputClass.prototype,
        name,
      );
 
      descriptor &&
        Object.defineProperty(outputClass.prototypename, descriptor);
    });
  });
}
 
applyMixins(Mixed, [One, Two]);
 
const MixedClass = new Mixed();
 
MixedClass.num1 = 1;
MixedClass.num2 = 2;
MixedClass.num3 = 3;
MixedClass.printA();
MixedClass.printB();
cs

 

하지만 여기서 주의해야 할 점이 있다. 바로 데코레이터를 사용하지 못한다는 것이다. 만약 nestjs의 dto 관련해서 다중 상속을 사용해야 할 경우에는 사용할 수 없다는 것을 염두해 두어야 할 것이다.

 

반응형

'프로그래밍 언어 > JS TS' 카테고리의 다른 글

JSON 데이터 엑셀로 저장하기  (0) 2022.09.25
JS 코딩테스트 준비하기  (0) 2022.09.24
Typescript 유틸리티 타입 탐방하기  (0) 2022.07.30
Object 전체 순회하기  (0) 2022.07.13
TS 데코레이터  (0) 2021.09.15