typescript - 如何使 Typescript 检查器根据属性选择正确的联合类型
问题描述
我有一个数据网格,用户可以在其中对数据进行分组。这意味着行的数据可以是其数据的类型,也可以是分组行的数据。
这意味着在某些情况下,用户必须检查行的类型才能执行正确的操作——例如返回行的唯一 ID。
问题是 TS 检查器仅在属性存在于两种类型中时才选择正确的类型:
interface Athlete {
id: string
name: string
// Works with this but inconvenient to force the user to
// add this to all their items
// isGroup: false
}
interface GroupRow {
isGroup: true
groupId: string
}
type Row = Athlete | GroupRow
function getRowId(row: Row) {
return row.isGroup ? row.groupId : row.id // TS Error
}
游乐场:链接
似乎 TS 检查器应该能够确定正确的类型,因为isGroup
在 中永远不会是真的(或定义)Athlete
,但不幸的是它不能。而且我不想:
a) 让用户添加一个isGroup: false
类型Athlete
和他们的数据
b) 每次row
引用时都让用户隐式转换为正确的类型,例如(row as GroupRow).isGroup ? (row as GroupRow).groupId : (row as Athlete).id
如何让 TS 检查器推断出正确的类型?
解决方案
推荐阅读
- python - 如何使用移位在时间戳两行之间进行减法 - Pandas Python
- c++ - 作为一般经验法则,我应该更喜欢直接列表初始化而不是复制初始化吗?
- python - 基于硒日期的刮表
- java - 如何使用 Apache-POI 为幻灯片中的链接视频创建 pptx 文件
- git - 当我选中“阻止命令行推送”复选框时,为什么我不能推送?
- azure - 将域的子文件夹映射到 azure app servive
- javascript - 如何使用 lodash 在 javascript 中实现多级排序?
- android - 如何在加载应用程序时存储未来数据以供进一步使用?# 颤动
- assembly - 如何堆叠(推送)xPSR?
- javascript - js中的定时动作(每秒帧数)