TypeScript 装饰器不适用于派生类

时间:2021-02-10 13:56:48

标签: typescript decorator

问题

我正在做一个项目,我想为一个类制作一个装饰器,但我收到这个错误:

Type 'typeof Controller' is not assignable to type 'typeof MainController'.
    Cannot assign an abstract constructor type to a non-abstract constructor type.

我的代码

这是我写的代码:

文件 1

export function myDecorator(arg: string) {
    return (cls: typeof Base) => {
        // more code
        return cls;
    };
}
export function otherDecorator(arg: string) {
    return (cls: Base, ...) => {
        // more code
    };
}
export abstract class Base {
    // some methods
}

文件 2

import { myDecorator, otherDecorator, Base } from "./file1";
@myDecorator("some text") // here I get the error
class Derived extends Base {
    @otherDecorator("other text") // everything is fine here
    public myMethod() {}
}

我的问题是什么?因为通常应该可以做一些事情。或者你有其他建议给我吗?我只想将 myDecorator 限制为从 Base

派生的任何类

编辑:我解决了这个问题。往下看。

1 个答案:

答案 0 :(得分:1)

我找到了答案:我更改了 myDecorator 返回函数的签名:

return <T extends Controller>(cls: Constructor<T>): Constructor<T> => {}

Constructor<T> 就是这样的类型:

export type Constructor<Class, Args extends any[] = any[]> = new (...args: Args) => Class;

现在可以使用了。