首页 > 解决方案 > 如何使 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 检查器推断出正确的类型?

标签: typescript

解决方案


您可以使用in运算符来缩小类型:

function getRowId(row: Row) {
  return 'isGroup' in row ? row.groupId : row.id
}

操场


推荐阅读