寻找类型保护解决方案(TypeScript)

Looking for type-guarding solution (TypeScript)

我在尝试进行 TypeScript 类型保护时遇到了一些问题。基本上我想做的是检查 path[aPath] 是否是一个包含 Type1 类型元素的数组,然后推送到该数组。但是,即使在使用 Array.isArray() 检查该值是否为数组后,我也无法执行此操作。显然我在类型保护方面做错了,也许我所做的根本不是类型保护,所以一些反馈和解决方案可能会很棒。

如果这有帮助,将鼠标悬停在 path[aPath].push(...) 上 linter 会给出此错误:

这个表达式是不可调用的。 并非所有 'Type1[] | ((...items: Type1[]) => number)' 类型的成分都是可调用的。 类型 'Type1[]' 没有调用 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
  }
});```

Typescript 无法保护嵌套属性,因为检查对象 属性 是否未发生变化非常复杂。类型保护仅适用于变量中的值。因此将条目复制到局部变量中:

 const el = path[aPath];

然后你可以打字el