Home > Back-end >  TypeScript inconsistency - why does compiler allow object property value assignment but no method re
TypeScript inconsistency - why does compiler allow object property value assignment but no method re

Time:03-22

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). This is somewhat funny, since the compiler assumes that this web app, which will be ultimately ran by a browser might have no window - is there any situation for an Angular-based solution, where this would be a possible case?

Anyway, 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 PoC

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)?

CodePudding user response:

$ is a third-party function. The return type of this function is specified in GitHub.

The error message means that the returned value from $(window) is possibly undefined. You can use optional chaining $(window)?.width().

The error has nothing to do with width.

Even though there will always be a window object, the function $ has a return type that's possibly undefined.

  • Related