打字稿重载函数

时间:2020-02-04 23:05:24

标签: node.js typescript express intellisense

我正在尝试在listen对象上调用重载函数Server。似乎正在发生的事情是,即使存在匹配的定义,编译器也会将错误的方法与调用匹配。我不确定如何进行调试。

Server对象具有以下定义

class Server extends events.EventEmitter {
        constructor(connectionListener?: (socket: Socket) => void);
        constructor(options?: { allowHalfOpen?: boolean, pauseOnConnect?: boolean }, connectionListener?: (socket: Socket) => void);

        listen(port?: number, hostname?: string, backlog?: number, listeningListener?: () => void): this;
        listen(port?: number, hostname?: string, listeningListener?: () => void): this;
        listen(port?: number, backlog?: number, listeningListener?: () => void): this;
        listen(port?: number, listeningListener?: () => void): this;
        listen(path: string, backlog?: number, listeningListener?: () => void): this;
        listen(path: string, listeningListener?: () => void): this;
        listen(options: ListenOptions, listeningListener?: () => void): this;
        listen(handle: any, backlog?: number, listeningListener?: () => void): this;
        listen(handle: any, listeningListener?: () => void): this;

...

以下代码可以编译并正常运行:

server.listen(8080)

以下内容根本无法编译:

server.listen(8080, '0.0.0.0')

智能报告

No overload matches this call.
  The last overload gave the following error.
    Argument of type '"0.0.0.0"' is not assignable to parameter of type '() => void'.ts(2769)
net.d.ts(193, 9): The last overload is declared here.

和编译器类似地抱怨:

node_modules/ts-node/src/index.ts:261
    return new TSError(diagnosticText, diagnosticCodes)
           ^
TSError: ⨯ Unable to compile TypeScript:
lib/app.ts(333,35): error TS2345: Argument of type '"0.0.0.0"' is not assignable to parameter of type '() => void'.

    at createTSError (node_modules/ts-node/src/index.ts:261:12)
    at getOutput (node_modules/ts-node/src/index.ts:367:40)
    at Object.compile (node_modules/ts-node/src/index.ts:558:11)
    at Module.m._compile (node_modules/ts-node/src/index.ts:439:43)
    at Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Object.require.extensions.(anonymous function) [as .ts] (node_modules/ts-node/src/index.ts:442:12)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)

谢谢!

2 个答案:

答案 0 :(得分:1)

我今天也遇到过同样的问题。 不确定发生这种情况的真正原因,但是我已通过通过方法call传递参数来解决此问题。

server.listen.call(server, 4000, '0.0.0.0', () => {
  console.log(server.address()) // output is { address: '0.0.0.0', family: 'IPv4', port: 4000 }
});

答案 1 :(得分:0)

您的类型不匹配。 process.env.PORT 是字符串类型,而函数接受数字。 这应该可以解决它:

instru_id date          sect_classif  sect_classif_instru_weights
123       31.03.2020    35            0.0054
456       31.03.2020    45            0.0060
789       31.03.2020    50            0.0027
1111      31.03.2020    50            0.0027