Reputation: 3
I'm having some issues with attempting to do TypeScript typeguarding. Basically what I want to do check if path[aPath] is an array containing elements of type Type1, and then push onto that array. However, I'm not able to do this even after checking whether the value is an array or not with Array.isArray(). Obviously I'm doing some wrong with type-guarding, and maybe what I'm doing isn't type guarding at all, so some feedback and maybe a solution would be amazing.
If this helps, hovering over path[aPath].push(...) the linter gives this 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 }); // Push does not work here, after checking if the value is an array
}
});```
Upvotes: 0
Views: 48
Reputation: 138557
Typescript cannot guard nested properties, as it's quite complex to check if an object property was not mutated. Typeguarding only works for values in variables. Thus copy the entry into a local variable:
const el = path[aPath];
You can then typeguard el
.
Upvotes: 1