TypeScript重载函数签名带有布尔参数和依赖返回类型



我想调用一个基于输入布尔参数的返回类型的函数,因此如果参数为假,则返回某些类型,如果参数为真,则返回某些其他类型。我认为重载在这种情况下是完美的,但是TypeScript不允许我使用它们:

hello(foo: false): ''
hello(foo: true): 'bar' {
if(foo) {
return 'bar'
} else {
return ''
}
}
因为我得到This overload signature is not compatible with its implementation signature.

我应该使用其他东西,修改这段代码或只是切换到多个函数与不同的名称和类似的行为?

尝试创建一个重载函数是不正确的。每个变体必须与底层实现兼容

在你的代码中:

  • 底层实现只接受true并返回bar
  • 因此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);

最新更新