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

122
Visualizações
Why does Typescript flag a possible undefined value on array length check with greater than but not equals?

Given this snippet of a React component:

const AccountInformation = (props: { readonly accountData: AccountData | undefined | null }) => {
  const hasMultipleAccounts: boolean = props.accountData?.customerAccounts?.length === 1 ? false : true
...

Why does Typescript complain that props.accountData?.customerAccounts?.length is possibly undefined when I check if it is greater than 0 (> 0) but the error goes away when I check if it is equal to 1 (=== 1)?

Is this a case where JS is doing something weird with an undefined property being interpreted as 0?

Writing it this way eliminates the error, but I'm trying to understand the behavior.

  const hasMultipleAccounts: boolean = props.accountData?.customerAccounts?.length ?? 0 > 1 ? : true : false
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

More simply, you're asking why TypeScript complains about the second of these statements:

console.log(undefined === 1);   // false
console.log(undefined > 0);
//          ^−−−− Object is possibly 'undefined'.(2532)

...because any property access operation with optional chaining in it has undefined as one of its possible result values.

=== is more general than > is. === is used to see if the type of value of the operands match. But > is used to either compare two numbers or to compare two strings for relative "greater"-ness. TypeScript also prevents mixing those two:

console.log("1" > 0);
//          ^−−− Operator '>' cannot be applied to types 'string' and 'number'.(2365)
console.log(1 > "0"");
//          ^−−− Operator '>' cannot be applied to types 'number' and 'string'.(2365)

In JavaScript, we're (fairly) used to implicit conversion in these situations, but TypeScript's job is to apply strict typing, and so implicit conversion is generally not allowed. In JavaScript, undefined > 0 becomes NaN > 0 which is false (as is undefined <= 0). But TypeScript sees that as the error it likely is, and flags it up for you.

(Playground link for all of the above.)

about 4 years ago · Juan Pablo Isaza Relatório

0

If you want to use length > 0 you'll need null coalescing:

const i: number | undefined = undefined;

if (i ?? 0 > 0) {
}
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