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

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

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 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