Typescript方法重载不同类型的参数但相同的响应

Mr.*_*r.B 4 methods overloading typescript

我需要使用 TypeScript 重载一个方法。

FooModel有 6 个参数,但 2 个字符串参数是唯一的强制参数。因此,我不想每次想使用myMethod时都创建FooModel,而是想重载myMethod并在其中创建一次FooModel,然后在返回之前创建其余逻辑。

我已经根据迄今为止在网上找到的内容尝试过此操作,但出现以下错误:

TS2394: This overload signature is not compatible with its implementation signature.
Run Code Online (Sandbox Code Playgroud)

该错误的解决方案与我的方法不兼容

    static async myMethod(model: FooModel): Promise<BarResult>
    static async myMethod(inputText: string, outputText: string): Promise<BarResult>{
         //implementation;
      return new BarResult(); //Different content based on the inputs
    }
Run Code Online (Sandbox Code Playgroud)

Win*_*ing 7

问题

\n

来自 TypeScript 的文档:

\n
\n

重载签名和实现签名

\n

这是造成混乱的常见原因。通常人们会编写这样的代码,但不明白为什么会出现错误:

\n
\n
function fn(x: string): void;\nfunction fn() {\n  // ...\n}\n// Expected to be able to call with zero arguments\nfn();\n^^^^\nExpected 1 arguments, but got 0.\n
Run Code Online (Sandbox Code Playgroud)\n
\n

同样,用于编写函数体的签名从外部不能是\xe2\x80\x99\xe2\x80\x9cseen\xe2\x80\x9d。

\n

从外部看不到实现的签名。当编写重载函数时,您应该始终在函数的实现之上有两个或多个签名。

\n

实现签名还必须与重载签名兼容。例如,这些函数有错误,因为实现签名\xe2\x80\x99与重载不以正确的方式匹配:

\n
\n
function fn(x: boolean): void;\n// Argument type isn\'t right\nfunction fn(x: string): void;\n         ^^\nThis overload signature is not compatible with its implementation signature.\n\nfunction fn(x: boolean) {}\n
Run Code Online (Sandbox Code Playgroud)\n
function fn(x: string): string;\n// Return type isn\'t right\nfunction fn(x: number): boolean;\n         ^^\nThis overload signature is not compatible with its implementation signature.\n\nfunction fn(x: string | number) {\n  return "oops";\n}\n
Run Code Online (Sandbox Code Playgroud)\n

\xe2\x80\x93有关重载和实现签名的 TypeScript 文档

\n

在您的情况下,您定义了以下重载签名:

\n
static async myMethod(model: FooModel): Promise<BarResult>\n
Run Code Online (Sandbox Code Playgroud)\n

但实现签名没有重叠。实现签名中的第一个参数是stringwhile 重载是FooModel,而实现签名中的第二个参数是stringwhile 重载是undefined

\n
static async myMethod(inputText: string, outputText: string): Promise<BarResult>{\n
Run Code Online (Sandbox Code Playgroud)\n

解决方案

\n

将当前的实现签名转换为重载,并添加与两个重载兼容的实现签名:

\n
class Foo {\n  static async myMethod(model: FooModel): Promise<BarResult>;\n  static async myMethod(inputText: string, outputText: string): Promise<BarResult>;\n  static async myMethod(modelOrInputText: string | FooModel, outputText?: string): Promise<BarResult>{\n   //implementation;\n    return new BarResult(); //Different content based on the inputs\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

\xe2\x80\x93 TypeScript 游乐场

\n