繁体   English   中英

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

[英]Typescript Method overloading for different type of parameters but same response

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

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

我已经根据到目前为止在网上找到的内容进行了尝试,但出现以下错误:

TS2394: This overload signature is not compatible with its implementation signature.

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

    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
    }

问题

来自 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 文档

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

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
  }
}

打字稿游乐场

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM