我有以下代码:
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错误。
我不确定处理混合类型数组的最佳方法是什么?
谢谢!
答案 0 :(得分:1)
.map()
中的函数应返回一个值。
这是将B
列表映射到A
的方法:
const aItems = items.map((item: B): A => {
return {
...item,
age: 40
}
});
这里发生的是,我们使用spread syntax克隆给定的item
并为其分配了新的age
属性。
此外,如果不必同时拥有A
和B
这两种类型,您还可以将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
...
}
});