I am developing an Angular project using jQuery and noticed a strange anomaly. Look at the below TypeScript code from an Angular component class:
let foo :any | undefined = window.innerWidth * 0.26; // first line has no error
let bar :any | undefined = $(window).width() * 0.26; // second line has an error
The second line returns a compiler error: Object is possibly 'undefined'.ts(2532). Let us assume that there is such a case and the compiler is right, when the window object was somehow not initialized and look at this code;
let asd :number = window.innerWidth * 0.26; // third line also has no error
In this case, there can be two errors (see this link for reference);
window object has no innerWidth property defined, so asd will receive undefined as value, which is not of number type, so the compiler should throw Type 'undefined' is not assignable to type 'number'.ts(2322) error or the Object is possibly 'undefined'.ts(2532) errorwindow object was not instantiated, in which case it's type is null, so asd will receive no value and the program will return with ReferenceError.For proof of concept, see this snapshot from w3schools' TryIt editor;
So, my question is: why does the TypeScript compiler show error for the value assignment with jQuery method (first line), but no compiler error using the native JS object property approach (second and third line)?
The return type of
$(window).width()
is
number | undefined
The multiplication
$(window).width() * 0.26
is only allowed for two numbers. You have to handle the case for undefined. I would use a temporary variable and the conditional ternary operator:
const width = $(window).width();
let bar :any | undefined = width ? width * 0.26 : undefined;
The other lines don't cause an error because
window.innerWidth
has type
number