【问题标题】:TypeScript union check for existence of object keyTypeScript 联合检查对象键是否存在
【发布时间】:2021-01-09 06:17:02
【问题描述】:

我有一个接受负载的函数,该负载的一部分是data 属性,它可以是对象数组或具有特定属性的对象。根据负载上是否提供了某个键,在此示例中propA,我想返回该键的值,或默认值 150。我为数据属性创建了一个联合类型,见此处FunctionInterface 示例。

问题是这会导致 TS 错误...Property 'propA' does not exist on type 'Record<string, unknown>[]'.

如何更新我的函数接口或函数体以使用这样的东西?

interface FunctionInterface {
    data: Record<string, unknown>[] | { propA: number, propB?: string[] }
}

function myFunction(payload: FunctionInterface) {
    return payload.data.propA || 150;
}

const result1 = myFunction({ data: { propA: 4 } }); // expect 4
const result2 = myFunction({ data: [{ 'a': 1, 'b': 2 }, { 'a': 3, 'b': 4 }] }); // expect 150

TS Playground example

【问题讨论】:

    标签: typescript


    【解决方案1】:

    Typescript 抱怨,因为它不允许访问可能不存在的属性。

    这里的data prop 属性要么是数组,要么是对象,所以你需要处理这两种情况。

    最简单的方法可能是检查.data是否是一个数组,然后返回默认值,否则返回属性。

    function myFunction(payload: FunctionInterface) {
        return Array.isArray(payload.data) ? 150 : payload.data.propA
    }
    

    这是有效的,因为一旦你测试了 data 是否是一个数组,那么 typescript 就会记住这一点,并且知道如果检查失败,那么该值必须是联合的唯一其他成员。

    Playground

    【讨论】:

      猜你喜欢
      • 2013-09-26
      • 2014-03-19
      • 2020-06-18
      • 2021-11-25
      • 2019-11-12
      • 2014-01-15
      相关资源
      最近更新 更多