Issue
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?
Solution
Your attempt to create an overload function is incorrect. Each variant must be compatible with the underlying implementation
In your code:
- underlying implementation accepts only
true
and returnsbar
- thus
hello(foo: false): ''
is not compatible with it
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);
Answered By - Lesiak
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.