0

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.

3
  • Use an array instead of so many standalone variables, usually Commented Jun 18, 2021 at 4:31
  • @CertainPerformance When I made array util, type is not inferred by VSCode Commented Jun 18, 2021 at 4:41
  • @undefined Inside the if block, either v1, v2 or v3 is/are Nullish, so TypeScript cannot narrow the type of any variable to Nullish type and thus all the variables will still be infered as unknown. Commented Jun 18, 2021 at 4:52

1 Answer 1

1

Something like this:

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

or for better readability:

if ([v1, v2, v3].some((v) => isNullish(v)) {}
Sign up to request clarification or add additional context in comments.

2 Comments

I already used this solution, but type is not inferred by VSCode.
Maybe v1, v2, v3 doesn't have type unknown.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.