reactjs - 映射 2 种不同类型的 TypeScript 数组,其条件为仅存在于一种类型上的属性?
问题描述
我有类型A
和B
. 是和Items
的数组。此代码有效:A
B
type A = {
foo: string;
isB: false;
}
type B = {
bar: string;
isB: true;
}
type Items = (A | B)[];
const myItems: Items = [
{
foo: 'First string';
isB: false;
},
{
bar: 'Second string';
isB: true;
}
]
myItems.map((item, index)=>{
if(item.isA) {
return <ComponentA key={index} {...item} />
}
return <ComponentB key={index} {...item} />
})
我试图简化它,所以该isB
属性只存在于B
类型上。
type A = {
foo: string;
}
type B = {
bar: string;
isB: true;
}
type Items = (A | B)[];
const myItems: Items = [
{
foo: 'First string';
},
{
bar: 'Second string';
isB: true;
}
]
myItems.map((item, index)=>{
if(item.isA) {
return <ComponentA key={index} {...item} />
}
return <ComponentB key={index} {...item} />
})
但是我收到一个错误:
类型“A”上不存在属性“isRest”。
解决方案
推荐阅读
- reactjs - 如何在 React 中编写服务类型的函数,该函数可以使用函数的输入参数获取然后返回数据
- mvvm - 如何将多个视图模型绑定到单个视图
- html - 是否可以有没有高度和宽度的可见元素?
- c++ - 无法编译 protoc 生成的 (C++) 类
- java - 字符串不能转换为 javax.jcr.Value
- html - 当焦点在输入文本中时,如何使 tab 键将焦点移动到选项下拉列表?
- python - 计算文件中单词的出现次数
- sql-server - 太多参数被传递给 DRILLDOWNLEVEL MDX 函数。不允许超过 3 个参数
- kubernetes - 通过 http 和 https 访问 Kubernetes 上的 .NET Core 应用程序
- ssl - 由中间 CA(go daddy)签署的有效证书不适用于少数客户端(docker alpine)