每当我这样调用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实例?为什么不呢?
问题是普通类和抽象类在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,
);