How to Effectively Use Type Predicates in TypeScript


(v): v is number => v !== null && v !== undefined
๐ง What Is a Type Predicate?
A type predicate is a way to tell TypeScript:
โIf this condition is true, then you can safely treat
v
as a specific type.โ
The syntax is:
(parameter): parameter is Type => condition
So in your case:
v
is the parameterv is number
is the type predicatev !== null && v !== undefined
is the condition
๐ What It Does
This function is used inside .filter()
to remove null
and undefined
, and tell TypeScript that the remaining values are definitely number
.
Without Type Predicate:
const arr = [1, null, 2, undefined];
const filtered = arr.filter(v => v !== null && v !== undefined);
// TypeScript still thinks: (number | null | undefined)[]
With Type Predicate:
const filtered = arr.filter(
(v): v is number => v !== null && v !== undefined
);
// TypeScript now knows: number[]
โ
You can now safely use .toLocaleString()
or other number methods without type errors.
๐งช Real Example
const salaries = [50000, null, undefined, 75000];
const cleanSalaries = salaries
.filter((v): v is number => v !== null && v !== undefined)
.map(s => `$${s.toLocaleString()}`);
Without the type predicate, TypeScript would complain about s.toLocaleString()
because s
might still be null
or undefined
.
๐ง TL;DR
Expression | What It Does |
(v): v is number => ... | TypeScript knows v is a number |
v => v !== null && v !== undefined | Works at runtime, but TS still unsure |
v => Boolean(v) | Removes all falsy values (including 0 ) |
Subscribe to my newsletter
Read articles from Abhinav Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Abhinav Kumar
Abhinav Kumar
๐ B.Tech CSE | ๐จโ๐ป Learning DSA & C++ | ๐ Building projects & writing what I learn | ๐ Currently solving LeetCode & exploring Git/GitHub