0

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?

4
  • var children:any = [] do this and its works. Commented Jul 20, 2022 at 9:33
  • 2
    @BrijeshKalkani No, never do that. Then you're losing all benefits you get from TypeScript. Commented Jul 20, 2022 at 9:33
  • var children: string | number | Date | Blob so use this. Commented Jul 20, 2022 at 9:35
  • @BrijeshKalkani That will also not work. Why would you think there are Blobs involved in this situation? Commented Jul 20, 2022 at 9:35

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.