TSLint 抱怨 属性 对于混合类型数组的元素不存在

TSLint complains about property does not exist for an element of mixed typed array

我有如下一段代码:

    interface TileA {
      imageUrl: string;
    }

    interface TileB {
      videoUrl: string;
    }

    interface TileC {
      thumbnailUrl: string;
    }

    interface Curation {
      items: (TileA | TileB | TileC)[];
    }

    const curations: Curation[] = SOME_DATA;

    curations.map((curation) => {
        curation.items.map((item) => {
          if (typeof item.videoUrl != 'undefined') {  //  getting a TS2339 complaining videoUrl is not a property
            // do something 
          }
        });
    });

如图所示,当我尝试将 属性 videoUrl 分配给某个项目时,TS 抱怨无效 属性? 我猜这是因为它不知道实际类型的项目是什么?我尝试将其投射到特定的 Tile,但投射也会导致 TSLint 错误。

我不确定处理混合类型数组的最佳方法是什么?

谢谢!

.map() 中的函数应该 return 一个值。 以下是将 B 列表映射到 A 的方法:

const aItems = items.map((item: B): A => {
    return {
        ...item,
        age: 40
    }
});

这里发生的是我们使用 spread syntax 克隆给定的 item 并将新的 age 属性 分配给它。

此外,如果不需要同时使用 AB,您还可以将 age 设为可选 属性 并为所有类型使用单一类型项目:

interface A {
  name: string;
  age?: number;
}

编辑 2003 年 1 月:

interface Tile {
  type: "image" | "video" | "thumbnail";
  url: string;
}

...

curations.map((curation) => {
  curation.items.map((item) => {
    switch (item.type) {
      case "image":
        // do something
        // handle case for each type
      ...
    }
});