重载打字稿接口

时间:2021-05-06 18:20:33

标签: typescript interface overloading

为什么会出现这个错误?

我正在尝试使用打字稿超载,我已经阅读了文档。但是,我无法识别错误。有人要救吗?


export declare type TCallbackResponse<T> = ICallbackResponse<T>;

export type ICallbackResponse<T = string> = {
    (arg1: T, arg2: T, arg3: T): Promise<void>;
    (arg1: T, arg2: T): Promise<void>;
}


function handle<T = string>(name: string, call: ICallbackResponse<T>): void {

}

async function message(pattern: string, channel: string, message: string): Promise<void>
async function message(channel: string, message: string): Promise<void> {
    
}

async function pmessage(pattern: string, channel: string, message: string): Promise<void> {

}

handle('message', message) // Argument of type '(pattern: string, channel: string, message: string) => Promise<void>' is not assignable to parameter of type 'ICallbackResponse<string>'.(2345)
handle('message', pmessage) // Argument of type '(pattern: string, channel: string, message: string) => Promise<void>' is not assignable to parameter of type 'ICallbackResponse<string>'.(2345)

代码链接:https://www.typescriptlang.org/pt/play?#code/LAKApgHgDg9gTgFwAQBMwGMA2BDOYkICeU+AKgMLaaYBG26A1gEpgDOsAdq2ADykB8SALxIAkpWp1GLdjC68BAblChIsRAWL5xVWvWZtO3PsKSsEcAJYcA5oJEBvUEhdIAFLhsBGAFxJSADRIngBMfoHBcDYAzOEAlH4ACnAwALaWxgBuMJYo-Mogru6evv5BofFJKelZOXkFoAC+KiCgAGYArhzoCJZySAAW2BwomAqm5la2-G4c2KlgfpPWNkHoun46kvoyRgr8CUjZuUhOrSDN59ishN1Ind29-QusrNg2YG5Q2AgIYHAcJYWFZrIYcDhgTBAqarJAvN4faErQ7JNIZXjHPKga63dD3Lo9PocOFsBGfdBgiFQszA2xBeHvRY0mEo6roniYwRnIpNFo4u4PQn9KAMj5fH5-AFIulICnDKnS2GipnLWystG1XJclqXUBg0afADkysN9NJjLieuGBrcxvNH1NSBF9rAlpAQA

1 个答案:

答案 0 :(得分:0)

documentation 中,在您的情况下,以下两种方法称为实现签名,而不是重载签名 -

async function message(channel: string, message: string): Promise<void> {
    
}

async function pmessage(pattern: string, channel: string, message: string): Promise<void> {

}

来自文档 -

<块引用>

从外面看不到实现的签名。 在编写重载函数时,你应该总是有两个或 函数实现之上的更多签名。

由于您有多个调用签名,并且并非所有调用都匹配 中的所有签名ICallbackResponse,由于上述事实,请注意没有与 (arg1: T, arg2: T): Promise<void>; 匹配的签名观察缺少的第三个参数。

附带说明,通过仔细查看您的案例,您甚至不需要 (arg1: T, arg2: T): Promise<void>; 中的 ICallbackResponse 类型。