gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 18:29:09 24 4
gpt4 key购买 nike

我需要使用 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 的文档:

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 而重载是 未定义

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

关于类型脚本方法重载不同类型的参数但相同的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69674774/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com