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

304
Visualizações
Variable 'value' is used before being assigned

My code:

function test() {
  let value: number;

  for (let i = 0; i < 10; i++) {
    value = i;
    console.log(value);
  }

  return value;
}

test();

And got this:

Variable 'value' is used before being assigned

I found this very odd, as I had seen other similar problems that either used a callback or a Promise or some other asynchronous method, while I used just a synchronous for loop.

---------------------------------- Some update ------------------------

function test() {
  let value: number;

  for (let i = 0; i < 100; i++) {
    // a() is very expensive and with some effects
    const result = a(i)

    if(i===99) {
      value = result
    }

  }

  return value;
}

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Use the non-null assertion operator to ensure that "its operand is non-null and non-undefined in contexts where the type checker is unable to conclude that fact."

function test() {
  let value!: number;

  for (let i = 0; i < 10; i++) {
    value = i;
    console.log(value);
  }

  return value;
}

test();

Result

about 4 years ago · Juan Pablo Isaza Relatório

0

TypeScript can't infer that anything in the loop body runs - it doesn't check that i starts at 0, and the condition is i < 10, and that the body will run at least once as a result. This behavior is very similar to the following:

function test() {
  let value: number;
  if (Math.random() < 0.5) {
    value = 5;
  }
  return value;
}

which produces the same error.

For TS to know that the value really definitely is defined at the end, you need to make it completely unambiguous. Usually, the best way this is achieved is by defining and assigning to the variable once, with const, through array methods and helper functions - TS works best when reassignment is minimized.

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