If you find yourself utilizing a variable for various scenarios that involve different types, it may be a sign of an issue.
For example, if we assume that rootFolder
is of type Folder
and folder.childs
is of type Folder[]
, your code could potentially resemble the following:
const children: Folder[] = (folderPath === '/' ? [rootFolder] : folder.childs);
In fact, you can simplify it to just:
const children = (folderPath === '/' ? [rootFolder] : folder.childs);
This allows inference to handle the details for you.
If you prefer using an if
statement instead, you can do so as well:
let children: Folder[];
if (folderPath === '/') {
children = [rootFolder];
} else {
children = folder.childs;
}
Rest assured, TypeScript will recognize that the variable is always assigned after the if
statement, even without an initial value.