1

每当我这样调用 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 实例吗?为什么不?

4

1 回答 1

0

问题是普通类和抽象类在 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-05-23T08:24:25.633 回答