【问题标题】:Typescript Method overloading for different type of parameters but same responseTypescript方法重载不同类型的参数但相同的响应
【发布时间】:2021-10-22 09:50:31
【问题描述】:

我需要使用 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 methods overloading


【解决方案1】:

问题

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

【讨论】:

  • 这就像一个魅力。谢谢
猜你喜欢
  • 2015-10-26
  • 1970-01-01
  • 2014-10-10
  • 1970-01-01
  • 2020-04-30
  • 1970-01-01
  • 2020-06-11
  • 1970-01-01
  • 2016-07-30
相关资源
最近更新 更多