Recipes
›
Chapter 9: The Standard Library and External Type Definitions
Filtering Nullish Values
Recipe 9.8 from
The TypeScript Cookbook
type Truthy<T> = T extends "" | false | 0 | 0n ? never : T;
interface Array<T> {
filter(predicate: BooleanConstructor): Truthy<NonNullable<T>>[];
}
interface ReadonlyArray<T> {
filter(predicate: BooleanConstructor): Truthy<NonNullable<T>>[];
}
const array = [0, 1, 2, 3, ``, -0, 0n, false, undefined, null] as const;
const filtered = array.filter(Boolean);
const nullOrOne: Array<0 | 1> = [0, 1, 0, 1];
const onlyOnes = nullOrOne.filter(Boolean);