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

时间:2020-01-02 06:06:52

标签: arrays typescript tslint

我有以下代码:

    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错误。

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

谢谢!

1 个答案:

答案 0 :(得分:1)

.map()中的函数应返回一个值。 这是将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;
}

修改20/01/03:

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
      ...
    }
});