【问题标题】:Unable to resolve signature of Typescript decorator when imported from another file从另一个文件导入时无法解析 Typescript 装饰器的签名
【发布时间】:2018-01-06 20:39:06
【问题描述】:

鉴于以下情况:

decorator.ts

export function logStuff(target: Object, key: string | symbol, descriptor: TypedPropertyDescriptor<any>) {
    return {
        value: function (...args: any[]) {
            args.push("Another argument pushed");
            descriptor.value.apply(target, args);
        }
    };
}

Shell.ts

// Removed other imports for brevity
import logStuff = require("utils/log-decorator");

class Shell extends AnotherClass {
    constructor() {
        super();
        this.fooMethod("arg1");
    }

    @logStuff
    private fooMethod(arg1: string, arg2?: string) {
        console.log(`Arguments from original function: ${JSON.stringify(arguments)}`);
    }
}

export = Shell;

我收到此消息(为简洁起见缩短了文件路径):

在调用时无法解析方法装饰器的签名 表达。无法调用类型缺少调用的表达式 签名。键入'类型 “/utils/log-decorator”有 没有兼容的调用签名

但是,如果我将函数移动到 Shell.ts 的顶部,它编译时不会出错。有关如何处理此问题的任何建议?

【问题讨论】:

    标签: javascript typescript


    【解决方案1】:

    您的logStuff 可作为模块的导出成员使用。所以你必须像这样访问它:

    import logStuffModule = require("utils/log-decorator");
    //...
    @logStuffModule.logStuff
    private fooMethod(arg1: string, arg2?: string) { ... }
    

    或者使用 ES6 风格的导入:

    import { logStuff }  from "utils/log-decorator";
    
    // ...
    @logStuff
    private fooMethod(arg1: string, arg2?: string) { ... }
    


    或者您可以通过将导出对象设置为您的函数来修改您的模块,并像现在使用它一样使用它:
    // decorator.ts
    export = function logStuff() {}
    
    // Shell.ts    
    import logStuff = require("utils/log-decorator");
    
    // ...
    @logStuff
    private fooMethod(arg1: string, arg2?: string) { ... }
    

    【讨论】:

      猜你喜欢
      • 2018-01-07
      • 2016-07-26
      • 2018-12-03
      • 2016-10-08
      • 1970-01-01
      • 2016-11-24
      • 2019-04-18
      • 2020-01-30
      • 2021-07-06
      相关资源
      最近更新 更多