Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

176
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!