typescript / intermediate
Snippet
Filtering and Transforming Arrays Safely with Custom Type Guards
Standard Array.prototype.filter calls often fail to narrow optional or nullable elements in TypeScript. Implementing custom type predicates (`item is T`) ensures the output array type accurately excludes null and undefined values.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
type Item = { id: string } | null | undefined;function isPresent<T>(item: T | null | undefined): item is T {return item !== null && item !== undefined;}const rawList: Item[] = [{ id: "a" }, null, { id: "b" }, undefined];const cleanList = rawList.filter(isPresent);cleanList.forEach(item => console.log(item.id));
Breakdown
1
function isPresent<T>(item: T | null | undefined): item is T
Defines a generic user-defined type guard returning a type predicate assertion.
2
const cleanList = rawList.filter(isPresent);
Filters the array while simultaneously narrowing the return array type from Item[] to { id: string }[].