微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

TypeScript 装饰器不适用于派生类 文件 1文件 2

如何解决TypeScript 装饰器不适用于派生类 文件 1文件 2

问题

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

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

派生的任何类

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

解决方法

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

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

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

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

现在可以使用了。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。