问题
来自 TypeScript 的文档:
重载签名和实现签名
这是一个常见的混淆来源。经常有人会这样写代码,不明白为什么会报错:
function fn(x: string): void;
function fn() {
// ...
}
// Expected to be able to call with zero arguments
fn();
^^^^
Expected 1 arguments, but got 0.
同样,用于编写函数体的签名不能从外部“看到”。
从外部看不到实现的签名。在编写重载函数时,您应该始终在函数实现之上有两个或多个签名。
实现签名还必须与重载签名兼容。例如,这些函数有错误,因为实现签名没有以正确的方式匹配重载:
function fn(x: boolean): void;
// Argument type isn't right
function fn(x: string): void;
^^
This overload signature is not compatible with its implementation signature.
function fn(x: boolean) {}
function fn(x: string): string;
// Return type isn't right
function fn(x: number): boolean;
^^
This overload signature is not compatible with its implementation signature.
function fn(x: string | number) {
return "oops";
}
——TypeScript documentation on overload and implementation signatures
在您的情况下,您定义了以下重载签名:
static async myMethod(model: FooModel): Promise<BarResult>
但实现签名没有重叠。实现签名中的第一个参数是string,而重载是FooModel,而实现签名中的第二个参数是string,而重载是undefined。
static async myMethod(inputText: string, outputText: string): Promise<BarResult>{
解决方案
将你当前的实现签名变成一个重载,并添加一个与你的重载兼容的实现签名:
class Foo {
static async myMethod(model: FooModel): Promise<BarResult>;
static async myMethod(inputText: string, outputText: string): Promise<BarResult>;
static async myMethod(modelOrInputText: string | FooModel, outputText?: string): Promise<BarResult>{
//implementation;
return new BarResult(); //Different content based on the inputs
}
}
——TypeScript Playground