I want to understand why TypeScript can't infer the return type of the following function (whilst it is able to differentiate in the if-else statement):
function calc (arg: number|string) {
if (typeof arg === 'number') {
// here typescript knows arg is number type
return arg
} else if (typeof arg === 'string') {
// here typescript knows arg is string type
return arg
}
}
// infers test to be number|string|undefined
const test = calc(10)
And when we write the following function:
function calc (arg: number|string) {
return String(arg)
}
// infers test to be string
const test = calc(10)
Then it of course can infer the return type. But how come it cannot infer the return type of the first function while it does provide type safety in the different branches and it knows it gets a number type as arg?
Edit
I know how to solve it, but I really want to understand why it TypeScript can't do it?