클래스 변환기의 plainToClass :이 함수를 사용하여 일반 리터럴을 추상 클래스로 변환하는 방법은 무엇입니까?

얄프 시드 맨

plainToClass를 다음과 같이 호출 할 때마다 :

someClass: SomeClass = plainToClass(SomeClass, somePlain)

모든 것이 좋습니다. 그러나 일단 SomeClass를 추상으로 변경하고 위의 내용을 다음과 같이 다시 작성하십시오.

someAbstractClass: SomeAbstractClass = plainToClass(SomeAbstractClass, somePlain)

오류가 발생합니다.

No overload matches this call.
  Overload 1 of 2, '(cls: ClassType<BaseFeature>, plain: unknown[], options?: ClassTransformOptions): BaseFeature[]', gave the following error.
    Argument of type 'typeof BaseFeature' is not assignable to parameter of type 'ClassType<BaseFeature>'.
      Cannot assign an abstract constructor type to a non-abstract constructor type.
  Overload 2 of 2, '(cls: ClassType<SomeAbstractClass>, plain: object, options?: ClassTransformOptions): SomeAbstractClass', gave the following error.
    Argument of type 'typeof SomeAbstractClass' is not assignable to parameter of type 'ClassType<SomeAbstractClass>'

plainToClass를 사용하여 일반을 abstractClass 인스턴스로 변환하는 것이 가능하지 않습니까? 왜 안돼?

사탄 시간

문제는 일반 클래스와 추상 클래스가 TS에서 다른 서명을 갖는다는 것입니다.

export interface AbstractType<T> extends Function {
  prototype: T;
}

export type Type<T> = new (...args: any[]) => T;

그리고이 차이로 인해 TS는 오류를 보여줍니다.

일반적으로 추상 클래스의 인스턴스가 아니라이를 구현 한 클래스의 인스턴스 만 있어야합니다. 그럼에도 불구하고 해킹하여 any원하는 동작을 얻을 수 있습니다.

const someAbstractClass: SomeAbstractClass = plainToClass(
  SomeAbstractClass as any, // cast to fix the error.
  somePlain,
);

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관