TypeScript filter out nulls from an array

Cover Image for TypeScript filter out nulls from an array
Matheus Mello
Matheus Mello
published a few days ago. updated a few hours ago

A Quick Guide: Filtering Nulls from an Array in TypeScript

πŸ“ Hey there tech enthusiasts! Welcome to another exciting blog post on our tech blog. Today, we're going to tackle a common problem in TypeScript - how to filter out nulls from an array. πŸš€

The Setup: TypeScript with --strictNullChecks Mode πŸ’ͺ

First things first, let's set the context. We're working with TypeScript in --strictNullChecks mode. This means that our array contains nullable strings of type (string | null)[]. Our goal is to remove all the nulls and transform the array into type string[]. Easy peasy, right? Let's dig in. πŸ€“

The Challenge: Array.filter Won't Do the Trick 😱

At first glance, you might think that using the Array.filter method is the way to go. However, if you try it out, you'll quickly realize it won't work in this case. 😫

const array: (string | null)[] = ["foo", "bar", null, "zoo", null];
const filteredArray: string[] = array.filter(x => x != null);

Unfortunately, TypeScript throws an error: Type '(string | null)[]' is not assignable to type 'string[]'. Oops! We need a different approach. πŸ˜“

The Solution: A Single-Expression Magic ✨

Thankfully, we have a simple, single-expression solution for you. Meet the Array.reduce method. 😍

const array: (string | null)[] = ["foo", "bar", null, "zoo", null];
const filteredArray: string[] = array.reduce((acc, curr) => {
    if (curr != null) {
        acc.push(curr);
    }
    return acc;
}, []);

Woo-hoo! πŸŽ‰ By using Array.reduce, we can traverse our array and build a new array that only contains the non-null values. This way, TypeScript is happy, and we have our desired string[] type for filteredArray.

Handling Common Use Cases: Filtering Any Union Type πŸ”„

Now, let's say we have a more general problem - filtering an array of any union type by removing entries having a particular type from the union. Fear not, we've got you covered. 😎

For the most common use cases involving unions with null and maybe undefined values, we can utilize the NonNullish type provided by TypeScript. Here's an example:

type NonNullish<T> = T extends null | undefined ? never : T;

const array: (string | null)[] = ["foo", "bar", null, "zoo", null];
const filteredArray: NonNullish<typeof array[number]>[] = array.reduce((acc, curr) => {
    if (curr != null) {
        acc.push(curr);
    }
    return acc;
}, []);

By using the NonNullish type, we can filter out any specific type from a union, even if it's not limited to null and undefined values.

Your Turn: Engage with Us! πŸ’¬

✨And that's a wrap, folks!✨ We've tackled the challenge of filtering nulls from an array in TypeScript and even expanded the solution to handle common use cases involving union types.

Now, it's your time to shine. Have you ever encountered similar challenges while working with TypeScript arrays? Let us know in the comments below! We'd love to hear your experiences and any other TypeScript tips and tricks you have up your sleeve. πŸ‘‡

Stay tuned for more exciting tech content and be sure to subscribe to our blog for regular updates. Happy coding! πŸš€βœ¨


More Stories

Cover Image for How can I echo a newline in a batch file?

How can I echo a newline in a batch file?

updated a few hours ago
batch-filenewlinewindows

πŸ”₯ πŸ’» πŸ†’ Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Matheus Mello
Matheus Mello
Cover Image for How do I run Redis on Windows?

How do I run Redis on Windows?

updated a few hours ago
rediswindows

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! πŸš€ Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Matheus Mello
Matheus Mello
Cover Image for Best way to strip punctuation from a string

Best way to strip punctuation from a string

updated a few hours ago
punctuationpythonstring

# The Art of Stripping Punctuation: Simplifying Your Strings πŸ’₯βœ‚οΈ Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Matheus Mello
Matheus Mello
Cover Image for Purge or recreate a Ruby on Rails database

Purge or recreate a Ruby on Rails database

updated a few hours ago
rakeruby-on-railsruby-on-rails-3

# Purge or Recreate a Ruby on Rails Database: A Simple Guide πŸš€ So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? πŸ€” Well, my

Matheus Mello
Matheus Mello