diff --git a/lib/util/array.spec.ts b/lib/util/array.spec.ts new file mode 100644 index 00000000000000..57356be7de65df --- /dev/null +++ b/lib/util/array.spec.ts @@ -0,0 +1,12 @@ +import { isNotNullOrUndefined } from './array'; + +describe('util/array', () => { + it.each` + a | exp + ${null} | ${false} + ${undefined} | ${false} + ${{ name: 'foo' }} | ${true} + `('.isNotNullOrUndefined', ({ a, exp }) => { + expect(isNotNullOrUndefined(a)).toEqual(exp); + }); +}); diff --git a/lib/util/array.ts b/lib/util/array.ts index 6862260bc20bc5..0175fabf26f8e4 100644 --- a/lib/util/array.ts +++ b/lib/util/array.ts @@ -10,3 +10,12 @@ export function coerceArray(input: T[] | null | undefined): T[] { export function sortNumeric(a: number, b: number): number { return a - b; } + +// Useful for filtering an array so that it includes values that are not null or +// undefined. This predicate acts as a type guard so that the resulting type for +// `values.filter(isNotNullOrUndefined)` is `T[]`. +export function isNotNullOrUndefined( + value: T | undefined | null +): value is T { + return !is.nullOrUndefined(value); +}