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

181
Visualizações
How can I reuse a variable in typescript?

I want to use my variable children for different cases:

var children = [];

if (folderPath == '/') {
      var children = rootFolder;
} else {
      var children = folder.childs;
}

But I get the error message:

variable 'children' must be of type 'any[]' but here has type 'Folder[]'

What does this mean?

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

In general, if "using a variable for different cases" involves using them for different types, then you're Doing Something Wrong.

Assuming rootFolder is of type Folder, and folder.childs is Folder[], your code looks like it could be something like

const children: Folder[] = (folderPath === '/' ? [rootFolder] : folder.childs);

and in fact you should be able to just do

const children = (folderPath === '/' ? [rootFolder] : folder.childs);

too and let inference handle things.

If you want to use if, then

let children: Folder[];

if (folderPath === '/') {
   children = [rootFolder];
} else {
   children = folder.childs;
}

should be fine; TypeScript will notice the variable is always definitely set after that if, even if it has no initial value.

about 4 years ago · Santiago Trujillo 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