My question may have been phrased differently before. I have a function that takes two arguments, with each argument possibly being a number
, string
, or undefined
. The function returns a value that is guaranteed to be one of those types:
export function wideNarrow(wide:number|string|undefined,
narrow:number|string|undefined){
return isNarrowScreen() ? narrow : wide;
}
In one part of my application, I provide two numbers as arguments to the function:
wideNarrow(8, 0);
However, the inferred return type shows an error when trying to perform 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)
Even though it can be statically determined that this specific call will always return a number, TypeScript is still indicating that a string or undefined might be returned. How can I address this without disrupting existing functionality, considering that the function could potentially return undefined
, string
, number
, or combinations of these in other parts of the code?
I am using TypeScript 3.5.2/Vscode 1.36.1.