Reputation: 708
I would like to call a function with return type based on input boolean parameter, so it returns some type if parameter is false and some other type if parameter is true. I thought overloads are perfect for this case, but TypeScript won't let me use them:
hello(foo: false): ''
hello(foo: true): 'bar' {
if(foo) {
return 'bar'
} else {
return ''
}
}
Because I get This overload signature is not compatible with its implementation signature.
Should I use something else, modify this code or just switch to multiple functions with different names and similar behaviour?
Upvotes: 1
Views: 987
Reputation: 26006
Your attempt to create an overload function is incorrect. Each variant must be compatible with the underlying implementation
In your code:
true
and returns bar
hello(foo: false): ''
is not compatible with itfunction 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);
Upvotes: 2