Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

302
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda