undefined
undefined

Reputation: 1158

Typescript: How can I check multiple variables are nullish?

Context

I made isNullish function to check a specific variable is null or undefined. This function is implemented like below.

type Nullish = null | undefined;
const isNullish = (target: unknown): target is Nullish => target == null; 

Problem

I use this utility in many places, but it is annoying when to check many variables.

if (isNullish(v1) || isNullish(v2) || isNullish(v3)......) {}

In this situation, how can I achieve better solution for this? I'm not good at typescript, so it maybe easy question. Sorry for this and thanks for your reading.

Upvotes: 0

Views: 642

Answers (1)

Mr_Green
Mr_Green

Reputation: 41872

Something like this:

if ([v1, v2, v3].some(isNullish)) {}

or for better readability:

if ([v1, v2, v3].some((v) => isNullish(v)) {}

Upvotes: 1

Related Questions