TS - abstract Classes and Members

00_8_3·2023년 5월 11일
0

typescript

목록 보기
6/8

abstract Classes and Members

생성자 시그니처 타입

abstract class T {}

type ConstructorType = new () => T 

와 같은 형태

기존

추상화 객체는 직접 인스턴스화가 불가능하다 사용하려면
추상화 객체를 상속받거나 구현된 객체를 통해 인스턴스화 가능하다.

기존에는 이 부분을 몰라서 어차피 js로 트랜스파일 하면 타입이 제거되어 실행이 되니깐
ts-ignore로 예외 처리해서 사용했다.

abstract class Test {
	constructor() {
    	...
    }
}
  
class ITest extends Test {

	constructor() {
    	...
    }
}
  
  
class Wallet {
	constructor(algorithms: Array<typeof Test> ) {
        // @ts-ignore
    	this.adapters = algorithms.map( i => new i() )
    // 에러 발생
    // Cannot create an instance of an abstract class.
    	...
    }
}

new Wallet([ITest])
  

수정

...

class Wallet {
	constructor(alog: (new () => Test)[] ) {
   		... 
    }
}

new Wallet([ITest])

new Wallet([ITest, Test]) // 에러 발생. 
// Cannot assign an abstract constructor type to a non-abstract constructor type.

참고

https://www.typescriptlang.org/docs/handbook/2/classes.html#abstract-classes-and-members

0개의 댓글