繁体   English   中英

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()的函数应该返回一个值。 以下是将B的列表映射到A的方法:

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

这里发生的是我们使用传播语法克隆给定的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
      ...
    }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM