A utility for null and undefined array filtering in TypeScript
In TypeScript, it's common to transform an array of objects into an array containing a specific property from those objects, which may potentially be
undefined. For instance, let's say we want to compile a list of our users' websites, but some users might not have a website.
We can start with an interface and an array of user objects:
To create an array of their websites, we could initially attempt this:
However, this leads to the
websites variable having the type
(string | undefined), which isn't ideal.
Subsequently, you might try filtering out the undefined values:
websites still remains of type
(string | undefined).
This is where the
notNullOrUndefined function proves useful:
It checks whether the provided item is either null or undefined and provides TypeScript with a type hint, resulting in a cleaner and more precise
In summary, the
notNullOrUndefined function assists in filtering out null or undefined values when working with arrays of potentially nullable properties, leading to a more refined and expected data type.
Published: September 14, 2023 at 1:56 AM
Edited: September 16, 2023 at 1:51 PM