Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

291
Views
TypeScript inconsistency - why does compiler allow object property value assignment but no method return value assignment?

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

  1. 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) error
  2. window 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;

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!