简体   繁体   English

从另一个文件导入时无法解析Typescript装饰器的签名

[英]Unable to resolve signature of Typescript decorator when imported from another file

Given the following: 给定以下内容:

decorator.ts 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 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;

I get this message (shortened the file path for brevity): 我收到此消息(为简洁起见,缩短了文件路径):

Unable to resolve signature of method decorator when called as an expression. 作为表达式调用时,无法解析方法装饰器的签名。 Cannot invoke an expression whose type lacks a call signature. 无法调用类型缺少调用签名的表达式。 Type 'typeof "/utils/log-decorator"' has no compatible call signatures 类型'typeof“ / utils / log-decorator”'没有兼容的呼叫签名

However, if I move the function to the top of Shell.ts, it compiles without errors. 但是,如果我将函数移到Shell.ts的顶部,它将编译而不会出现错误。 Any suggestions on how to handle this? 有关如何处理此问题的任何建议?

Your logStuff is available as an exported member of the module. 您的logStuff可作为模块的导出成员使用。 So you have to access it like: 因此,您必须像这样访问它:

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

Or use ES6-style imports: 或使用ES6样式的导入:

import { logStuff }  from "utils/log-decorator";

// ...
@logStuff
private fooMethod(arg1: string, arg2?: string) { ... }


Or you can modify your module by setting the export object as your function and use it like how you are using it now: 或者,您可以通过将导出对象设置为函数来修改模块,并像现在一样使用它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM