我想基于输入布尔参数调用一个带有返回类型的函数,因此它返回一些类型如果参数是false,而其他类型的返回类型是true。我认为重载对于这种情况是完美的,但是TypeScript不允许我使用它们:
hello(foo: false): ''
hello(foo: true): 'bar' {
if(foo) {
return 'bar'
} else {
return ''
}
}因为我得到了This overload signature is not compatible with its implementation signature.
我是否应该使用其他的东西,修改这段代码,或者只是切换到具有不同名称和相似行为的多个函数?
发布于 2022-11-13 11:01:03
创建重载函数的尝试是不正确的。每个变体必须与底层实现兼容。
在您的代码中:
bar
true并返回true hello(foo: false): ''与不兼容。
function hello(foo: true): 'bar'
function hello(foo: false): ''
function hello(foo: boolean): '' | 'bar' {
if(foo) {
return 'bar'
} else {
return ''
}
}
const aFoo = hello(true);
const anEmptyString = hello(false);https://stackoverflow.com/questions/74419442
复制相似问题