【发布时间】:2020-08-28 21:03:53
【问题描述】:
我需要显示两种可能类型(FirstType、SecondType)的项目的轮播。我的轮播组件需要一个数组作为输入,所以我将这些项目声明为联合的数组
type FirstType = {
a: 'first',
b: number
}
type SecondType = {
b: string
}
type Items = (FirstType | SecondType)[]
现在在我的渲染函数中,我得到了一个 FirstType | SecondType 类型的项目。我可以通过检查a 键的存在来识别类型,这是FirstType 上的一个常量:
const renderItem = (item: FirstType | SecondType) => {
if (item.a === 'first') {
// Here I know that item is FirstType
} else {
// Here I know that item is SecondType
}
}
但是这段代码给了我错误:
类型 FirstType | 上不存在属性“a”第二类
我应该如何根据打字稿进行这项检查?
【问题讨论】:
-
if ('a' in item) { -
如果只有
a的存在很重要,那么您只需将条件更改为if ('a' in item),如Buczkowski 所述。但是,如果值很重要(它必须是'first'),那么您需要一个自定义类型保护,正如 spender 的回答所描述的那样。
标签: typescript