【问题标题】:Typescript - Determine object subtype from union type by checking the presence of some propertiesTypescript - 通过检查某些属性的存在来确定联合类型中的对象子类型
【发布时间】:2020-08-28 21:03:53
【问题描述】:

我需要显示两种可能类型(FirstTypeSecondType)的项目的轮播。我的轮播组件需要一个数组作为输入,所以我将这些项目声明为联合的数组

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”第二类

我应该如何根据打字稿进行这项检查?

Playground link

【问题讨论】:

  • if ('a' in item) {
  • 如果只有a 的存在很重要,那么您只需将条件更改为if ('a' in item),如Buczkowski 所述。但是,如果值很重要(它必须是 'first'),那么您需要一个自定义类型保护,正如 spender 的回答所描述的那样。

标签: typescript


【解决方案1】:

可能最安全的方法是使用自定义type-guard

function isFirstType(item: FirstType | SecondType): item is FirstType {
  return (item as FirstType).a === "first"; //or however you want to differentiate
}

然后

const renderItem = (item: FirstType | SecondType) => {
  if (isFirstType(item)) {
    // item is narrowed to FirstType
  } else {
    // item is narrowed to SecondType
  }
}

【讨论】:

    猜你喜欢
    • 2018-01-11
    • 2020-09-27
    • 2023-01-19
    • 1970-01-01
    • 1970-01-01
    • 2022-11-23
    • 2021-07-06
    • 1970-01-01
    • 2021-01-09
    相关资源
    最近更新 更多