gpt4 book ai didi

typescript - 此重载签名与其实现签名不兼容

转载 作者:行者123 更新时间:2023-12-02 01:30:49 26 4
gpt4 key购买 nike

我有一个接受数字或字符串的函数,如果类型是字符串,则返回“字符串”,或者如果类型是数字,则返回数字。

代码:

function stringOr1(v: number): number;
function stringOr1(v: string): string;

function stringOr1(v: number | string) {
if (typeof v == 'string') {
return 'string';
}
else {
return 1;
}
}

const s1 = stringOr1('1');
const s2 = stringOr1(1);

TS 错误:

This overload signature is not compatible with its implementation signature.

我做错了什么?

最佳答案

只是不要让类型推断为返回类型进行键入,因为它返回 "string"| 1.

function stringOr1(v: number | string): number | string {
if (typeof v == 'string') {
return 'string';
}
else {
return 1;
}
}

编译器这样做的原因很简单,您没有使用任何变量,因此编译器推断返回类型不能比 "string"| 宽。 1.

关于typescript - 此重载签名与其实现签名不兼容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73363955/

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