I'm encountering challenges with TypeScript type guarding. My goal is to confirm if path[aPath] is an array containing elements of type Type1, and then add to that array. However, even after using Array.isArray() to check whether the value is an array or not, I'm still unable to achieve this. It seems like I may be making a mistake with my type guarding implementation, and it's possible that what I'm attempting isn't true type guarding. Any feedback and potentially a solution would be greatly appreciated.
When trying to hover over path[aPath].push(...), the linter displays the following error:
This expression is not callable. Not all constituents of type 'Type1[] | ((...items: Type1[]) => number)' are callable. Type 'Type1[]' has no call signatures.ts(2349)
type Type1 = {
url: string;
icon: number;
};
type Type2 =
| { [pathname: string]: Type1[] }
| { [pathname: string]: { [subpathname: string]: Type1[] } };
const path: Type2 = {};
path["hi"] = [{ url: "Hi", icon: 5 }];
path["hi"].push({ url: "ss", icon: 4 });
path["aaa"] = { aaa: [{ url: "ss", icon: 5 }] };
Object.keys(path).forEach((aPath) => {
console.log(Array.isArray(path[aPath]));
if (Array.isArray(path[aPath])) {
path[aPath].push({ url: "AA", icon: 4 }); // Unable to push here even after confirming it's an array
}
});