check if value is null or undefined in typescript

In TypeScript, you can check if a value is null or undefined using the === operator to compare against null or undefined. You can also use the typeof operator to determine the type of the value.

Here is an example of how to check if a value is null or undefined:

index.ts
let x: number | null | undefined = null;

if (x === null) {
  console.log("x is null");
} else if (x === undefined) {
  console.log("x is undefined");
} else {
  console.log("x is a number");
}

// Output: x is null
216 chars
12 lines

In this example, x can be a number, null, or undefined. We first check if x is null, and if so, we print a message. If x is not null, we check if it is undefined, and if so, we print a different message. If x is neither null nor undefined, we know that it is a number.

Alternatively, we can use the typeof operator to check the type of x, like this:

index.ts
let x: number | null | undefined = undefined;

if (typeof x === "undefined") {
  console.log("x is undefined");
} else if (x === null) {
  console.log("x is null");
} else {
  console.log("x is a number");
}

// Output: x is undefined
235 chars
12 lines

In this example, we first check if the type of x is "undefined", and if so, we print a message. If x is not undefined, we check if it is null, and if so, we print a different message. If x is neither undefined nor null, we know that it is a number.

gistlibby LogSnag