【问题标题】:filter to removed undefined items in typescript using object destructuring使用对象解构过滤以删除打字稿中未定义的项目
【发布时间】:2021-10-22 05:11:23
【问题描述】:

我想在仍然使用类型保护的同时使用对象解构。但是,在过滤掉未定义的对象键后,typescript 仍然会推断出未定义的类型。

我不想使用非空断言,因为我们的 linter 会抱怨。

例如:

type theDataStructure = {
 payloadKey1: string,
 payloadKey2: string,
 requiredForPayload?: string ,
 otherKeyNotNeededinPayload: string,
}

const unfilteredPayload: theDataStructure[] = getPayload()

unfilteredPayload
   .filter(({ requiredKey }) => requiredKey && arbitraryBusinessLogic(requiredKey)
   .map(({ payloadKey1, payloadKey2, requiredKey }) => sendPayLoad(payloadKey1, payloadKey2, requiredKey)

Typescript 的 requiredKey 类型仍然是 string |在 map 函数中未定义。

【问题讨论】:

    标签: typescript typeguards


    【解决方案1】:

    filter 不会改变数组的类型。 TS 存储库中的某处应该存在一个未解决的问题,请求传播类型缩小,因为这是一个常见的用例。

    // Still T[]:
    filter(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): T[];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-27
      • 2021-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多