我有一個TypeScript接口,它具有一個名爲「send」的函數,該函數被兩個允許的簽名重載。創建實現具有重載函數的接口的匿名對象
export interface ConnectionContext {
send(data: ConnectionData): void;
send(data: ConnectionData, timeout: number): Promise<ConnectionData>;
}
我試圖創建一個實現此接口的匿名對象:
const context: ConnectionContext = {
send: (data: ConnectionData, timeout?: number): void | Promise<ConnectionData> => {
//
}
};
然而,打字稿2.4.1是生產以下錯誤:
Error:(58, 15) TS2322:Type '{ send: (data: ConnectionData, timeout?: number | undefined) => void | Promise<ConnectionData>; }' is not assignable to type 'ConnectionContext'.
Types of property 'send' are incompatible.
Type '(data: ConnectionData, timeout?: number | undefined) => void | Promise<ConnectionData>' is not assignable to type '{ (data: ConnectionData): void; (data: ConnectionData, timeout: number): Promise<ConnectionData>; }'.
Type 'void | Promise<ConnectionData>' is not assignable to type 'Promise<ConnectionData>'.
Type 'void' is not assignable to type 'Promise<ConnectionData>'.
我知道我可以用一個類做到這一點,但如果有一些方法來做到這一點沒有一個我寧可不創建一個完整的類。
我一直有一個類似的問題,也對此一般性答案感到好奇。 – bcherny