TypeScript filter out nulls from an array

TypeScript, --strictNullChecks mode.

Suppose I have an array of nullable strings (string | null)[]. What would be a single-expression way to remove all nulls in a such a way that the result has type string[]?

const array: (string | null)[] = ["foo", "bar", null, "zoo", null];
const filterdArray: string[] = ???;

Array.filter does not work here:

// Type '(string | null)[]' is not assignable to type 'string[]'
array.filter(x => x != null);

Array comprehensions could’ve work but they are not supported by TypeScript.

Actually the question can be generalized to the problem of filtering an array of any union type by removing entries having one particular type from the union. But let’s focus on unions with null and perhaps undefined as these are the most common usecases.

17 Answers
17

Leave a Comment