簡體   English   中英

打字稿重載函數

[英]Typescript Overloaded Function

我正在嘗試調用重載函數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)

提前致謝!

我今天遇到了同樣的問題。 不確定發生這種情況的真正原因,但我已經通過方法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 }
});

您的類型不匹配。 process.env.PORT 是字符串類型,而函數接受數字。 這應該解決它:

const port = Number(process.env.PORT) || 3000;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM