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

Typescript Method overloading for different type of parameters but same response

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

FooModel 有 6 个参数,但是 2 个字符串参数是唯一的强制参数。因此,不是每次我想使用 myMethod 时都创建 FooModel,而是想重载 myMethod并在那里创建 FooModel 一次,然后在 return.

之前创建其余逻辑

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

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 的文档:

Overload Signatures and the Implementation Signature

This is a common source of confusion. Often people will write code like this and not understand why there is an error:

function fn(x: string): void;
function fn() {
  // ...
}
// Expected to be able to call with zero arguments
fn();
^^^^
Expected 1 arguments, but got 0.

Again, the signature used to write the function body can’t be “seen” from the outside.

The signature of the implementation is not visible from the outside. When writing an overloaded function, you should always have two or more signatures above the implementation of the function.

The implementation signature must also be compatible with the overload signatures. For example, these functions have errors because the implementation signature doesn’t match the overloads in a correct way:

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