I'm not sure if this has been asked under different terminology. I've got a function that takes two arguments, where both can (independently) be a number, string, or undefined. The returned value is statically guaranteed to be also one of those two arguments:
export function wideNarrow(wide:number|string|undefined,
narrow:number|string|undefined){
return isNarrowScreen() ? narrow : wide;
}
In some part of my app I pass two numbers to the function:
wideNarrow(8, 0);
However, the inferred return type is string|number, which shows an error with a numerical operation:
const extendedAreaHeight = 26;
const baseY = extendedAreaHeight + wideNarrow(8, 0);
Operator '+' cannot be applied to types '26' and 'string | number'.ts(2365)
and
Object is possibly 'undefined'.ts(2532)
It can be statically inferred that this particular call will always return a number, why is TypeScript not detecting it and still thinking that a string or undefined might be returned, and how can I fix it without breaking existing functionality (e.g. I may return undefined or string, string or number, undefined or number and any combination of these in other places that I call the function)?
I'm on TypeScript 3.5.2/Vscode 1.36.1.
function wideNarrow<T extends number|string|undefined>(wide:T, narrow:T){ ... }- ThomaswideNarrow(25, '20%')- Can Poyrazoğlureturn true ? narrow : wide;the typescript playground does not infer from this that the returned type will always betypeof narrow; return type stays a union typetypeof narrow | typeof wide- Thomasfunction wideNarrow<T extends number|string, U extends number|string>(wide:T, narrow:U){ ... }but you'll still have the problem that the returned type isstring|numberwhen you use the function with a string and a number. - Thomas