function f(x:boolean|string) { return x }
f(true) // boolean | string
Why can't typescript understand that the return value is a boolean?
function f(x:boolean|string) {
return typeof x === 'boolean' ? true : 'str'
}
f(true) // boolean | string
It can't understand this either.
Do I need to manually setup a function overload definition?
Typescript will not infer different return types based on type guards in the function. You can however define multiple function signatures for let the compiler know the links between input parameter types and result type:
function ff(x: boolean): boolean;
function ff(x: string): string;
// Implementation signature, not publicly visible
function ff(x: boolean | string): boolean | string {
return typeof x === 'boolean' ? true : 'str'
}