【问题标题】:class-transformer's plainToClass: How to use this function to convert the plain literal to an abstract class?class-transformer plainToClass:如何使用此函数将纯文字转换为抽象类?
【发布时间】:2020-05-26 21:25:14
【问题描述】:

每当我这样称呼 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 将plain 转换为abstractClass 实例吗?为什么不呢?

【问题讨论】:

    标签: typescript abstract-class class-transformer


    【解决方案1】:

    问题是普通类和抽象类在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,
    );
    

    【讨论】:

      猜你喜欢
      • 2020-06-07
      • 1970-01-01
      • 2021-06-07
      • 2021-08-01
      • 2020-06-07
      • 1970-01-01
      • 1970-01-01
      • 2020-07-24
      • 1970-01-01
      相关资源
      最近更新 更多