繁体   English   中英

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

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

给定以下内容:

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;

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

作为表达式调用时,无法解析方法装饰器的签名。 无法调用类型缺少调用签名的表达式。 类型'typeof“ / utils / log-decorator”'没有兼容的呼叫签名

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

您的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) { ... } 

暂无
暂无

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

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