问题描述 投票:0回答:1
Array.filter()

删除所有闻起来像

Vegetable
的所有东西的列表。我想打印其余物品的颜色。
我使用
型谓词

进行狭窄:

function isVegetable(item: Fruit | Vegetable): item is Vegetable {
  return "taste" in item;
}

const tastyStuff = healthyStuff
    .filter((item) => !isVegetable(item))
    .map((item) => item.color);  // error
当我尝试以上时,Typescript在我的
.map()
调用中给我一个错误:

Property 'color' does not exist on type 'Fruit | Vegetable'.

如果我用经典循环替换

filter()
呼叫,一切都按预期工作:

for

是我可以在
const tastyStuff = [];
for (const item of healthyStuff) {
  if (!isVegetable(item)) {
    tastyStuff.push(item);
  }
}

tastyStuff.map((item) => item.color); // this works
呼叫的情况下缩小我的联合类型的方式吗?

因此,您的方法中有两件事,一个是您传递给
Array.filter()
数组方法的函数是一个新的定义箭头函数,那么TS不能推断数组的返回类型只有

filter

,然后以您的示例实际工作,它是因为该变量被视为

Fruit
类型,因为您没有在声明中定义它。但这不是你想要的。

解决方案将是:
typescript union-types narrowing
1个回答
0
投票
any[]

以相反的方式进行,检查项目是否为
type Fruit = { name: string; color: string; }; type Vegetable = { name: string; taste: string; }; type HealthyStuff = Array<Fruit | Vegetable>; const healthyStuff: HealthyStuff = [ { name: "apple", color: "red" }, { name: "banana", color: "yellow" }, { name: "turnip", taste: "boring" }, ]; function isFruit(item: Fruit | Vegetable): item is Fruit { return !("taste" in item); } const tastyStuff = healthyStuff .filter(isFruit) .map((item) => item.color);
,并在
Fruit

方法中使用该功能。您可以检查TS游乐场

希望它帮助了
    

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.