【发布时间】: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