Predicate / type guard function, checks if the given property is neither null nor undefined.
Narrows the type of the given property within the object type from T | null | undefined to just T.
Two variants:
A simple function for direct calls (e.g. in if-statement-conditions). It asks for the object to check as well as the property.
The second variant is a factory-function which only gets the property. It returns a pre-configured predicate function for usage with functional calls like Array#filter.
Example:
const x: { a: number, b: string | undefined } = { a: 1, b: 'example' };
// simple usage: pass object and property path
if (isPropertyNotNil(x, 'b')) {
// type of x is now { a: number, b: string }
x.b.charAt(3); // safe to access b
}
// array usage: just pass the property to check
[x]
.filter(isPropertyNotNil('b'))
// type is now [{ a: number, b: string }]
.map(x => x.b.charAt(3)) // safe to access b
Predicate / type guard function, checks if the given property is neither null nor undefined. Narrows the type of the given property within the object type from
T | null | undefinedto justT.Two variants:
A simple function for direct calls (e.g. in if-statement-conditions). It asks for the object to check as well as the property.
The second variant is a factory-function which only gets the property. It returns a pre-configured predicate function for usage with functional calls like Array#filter.
Example: