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?
CodePudding user response:
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.