How to Effectively Use Type Predicates in TypeScript

Abhinav KumarAbhinav Kumar
2 min read
(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 parameter

  • v is number is the type predicate

  • v !== 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

ExpressionWhat It Does
(v): v is number => ...TypeScript knows v is a number
v => v !== null && v !== undefinedWorks at runtime, but TS still unsure
v => Boolean(v)Removes all falsy values (including 0)

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