我想在仍然使用类型保护的同时使用对象解构。然而,在过滤掉未定义的对象键之后,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 |在map函数中未定义。
发布于 2021-08-20 17:07:14
filter不会更改阵列的类型。在TS存储库中的某个地方应该有一个开放的问题,请求传播类型缩小,因为这是一个常见的用例。
// Still T[]:
filter(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): T[];https://stackoverflow.com/questions/68865701
复制相似问题