简体   繁体   中英

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

Given the following:

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;

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

However, if I move the function to the top of Shell.ts, it compiles without errors. Any suggestions on how to handle this?

Your logStuff is available as an exported member of the module. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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