Ticker

6/recent/ticker-posts

Ad Code

Responsive Advertisement

Typescript中,多类型数组遍历该如何定义?

以下代码中,声明a为两种对象的复合数组,遍历时我想同时取type cmd child的值,然后通过if来判断是否存在进行数据处理,该如何书写?

const a: (
  | { type: string; cmd: number }
  | { type: string; child: number[] })[] = [
  {
    type: "aaa",
    cmd: 111
  },
  {
    type: "bbb",
    child: [1, 2, 3, 4]
  }
];

// 报错 Property 'cmd' does not exist on type '{ type: string; cmd: number; } | { type: string; child: number[]; }'.
a.forEach(({ type, cmd, child }) => {
  // doSomething
});

Enregistrer un commentaire

0 Commentaires