I thought it was possible to use optional chaining (?.
operator) in inequalities, however I am getting a Typescript error saying my variable may be undefined.
I tried out the code below in an online TypeScript Plaground, so I can see that the compiled code of getSize1()
and getSize2()
are different, but I don't totally understand why.
interface Options {
maxHeight?: number;
}
function getSize1(width: number, options: Options) {
const height = width * 2;
if (height > options?.maxHeight) { // <-- Doesn't work
const newWidth = options.maxHeight / 2;
return [newWidth, height];
}
return [width, height];
}
function getSize2(width: number, options: Options) {
const height = width * 2;
if (options.maxHeight && height > options.maxHeight) { // <-- Works
const newWidth = options.maxHeight / 2;
return [newWidth, height];
}
return [width, height];
}
Why is the if
statement in getSize1()
different than in getSize2()
? Is there a shorthand syntax for getSize2()
?
CodePudding user response:
The optional chaining operator checks if the object you're trying to access is null or undefined, not the property.
This would be useful if options
were an optional argument.
function getSize1(width: number, options?: Options)
To check if the property is undefined you have two options.
Explicitly checking against undefined:
if (options.maxHeight !== undefined && height > options.maxHeight)
Checking against all falsy
values, which will include 0
as invalid:
if (options.maxHeight && height > options.maxHeight)
CodePudding user response:
In the first case the options?.maxHeight
has the same type as options.maxHeight
: number | undefined
(as it possibly is undefined). Therefore you are comparing the types number > number | undefined
, but typescript does not allow number > undefined
(what should 2 > undefined
mean?). Therefore this errors.
In the second case options.maxHeight && height > options.maxHeight
, the comparison is done on the types number > number
because it is already clear that it exists.