Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

293
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda