简体   繁体   English

用于验证数组的每个项目是否已定义的类型保护

[英]Type guard for verifying that each item of an array is defined

I was wondering if it's possible to create a type guard which checks if every item of an array is defined.我想知道是否可以创建一个类型保护来检查是否定义了数组的每个项目。 I already have a type guard for checking a single value, but having a solution that would do that for a whole array (with would be great.我已经有一个用于检查单个值的类型保护,但是有一个可以对整个数组执行此操作的解决方案(如果有的话会很棒。

To put it in code, I'm looking for something that would type guard the following:把它放在代码中,我正在寻找可以输入以下内容的东西:

// Input array type:
[ Something | undefined, SomethingDifferent | undefined ]

// Type guard resolving to:
[ Something, SomethingDifferent ]

Currently I have the following type guard to check a single item:目前我有以下类型保护来检查单个项目:

function isDefined<T>(value: T | undefined | null): value is T {
    return value !== null && typeof value !== 'undefined';
}

The logical implementation of the type guard is quite easy (especially when reusing the guard for a single value):类型守卫的逻辑实现非常简单(尤其是在为单个值重用守卫时):

function isEachItemDefined<T extends Array<unknown>>(value: T): ?? {
    return value.every(isDefined);
}

My use case for this would be filtering after using the withLatestFrom operator (RxJS).我的用例是在使用withLatestFrom运算符(RxJS)之后进行过滤。 I have an edge case where I'd like to filter out the "event" whenever any of the values is not defined.我有一个边缘情况,只要未定义任何值,我想过滤掉“事件”。

observable1.pipe(
    withLatestFrom(observable2, observable3, observable4), // <-- each returns value or undefined
    filter(isEachItemDefined),
    map(([ item1, item2, item3, item4 ]) => {
      // event if the logic works correctly,
      // typescript wouldn't recognise the items as defined
      // e.g. item2 is still "string | undefined"
    }),
);
function isDefined<T> (value: T | undefined | null): value is T {
    return value !== null && value !== undefined
}

function isEachItemDefined<T> (value: Array<T | undefined | null>): value is Array<T> {
    return value.every(item => isDefined<T>(item))
}

Technically, the isDefined<T>(item) call can just be isDefined(item) because Typescript can infer the <T> just as it does for the type of item , but I like being explicit here.从技术上讲, isDefined<T>(item)调用可以只是isDefined(item)因为 Typescript 可以推断出<T>就像它对item的类型所做的那样,但我喜欢在这里明确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM