Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to check for both `null` and `undefined`?

Since TypeScript is strongly-typed, simply using if () {} to check for null and undefined doesn't sound right.

Does TypeScript have any dedicated function or syntax sugar for this?

like image 299
David Liu Avatar asked Mar 10 '15 23:03

David Liu


People also ask

Does check for null and undefined?

Finally, the standard way to check for null and undefined is to compare the variable with null or undefined using the equality operator ( == ). This would work since null == undefined is true in JavaScript. That's all about checking if a variable is null or undefined in JavaScript.

How do you compare null and undefined?

Difference Between undefined and null Though, there is a difference between them: undefined is a variable that refers to something that doesn't exist, and the variable isn't defined to be anything. null is a variable that is defined but is missing a value.

Is null == undefined?

It means null is equal to undefined but not identical. When we define a variable to undefined then we are trying to convey that the variable does not exist . When we define a variable to null then we are trying to convey that the variable is empty.

How do you know if a Typecript is null or undefined?

To check for null or undefined , compare the value to both null and undefined , e.g. if (name === undefined || name === null) {} . If either of the two conditions is met, the variable stores a null or undefined value and the if block will run. Copied!


2 Answers

Using a juggling-check, you can test both null and undefined in one hit:

if (x == null) { 

If you use a strict-check, it will only be true for values set to null and won't evaluate as true for undefined variables:

if (x === null) { 

You can try this with various values using this example:

var a: number; var b: number = null;  function check(x, name) {     if (x == null) {         console.log(name + ' == null');     }      if (x === null) {         console.log(name + ' === null');     }      if (typeof x === 'undefined') {         console.log(name + ' is undefined');     } }  check(a, 'a'); check(b, 'b'); 

Output

"a == null"

"a is undefined"

"b == null"

"b === null"

like image 147
Fenton Avatar answered Sep 18 '22 14:09

Fenton


if( value ) { } 

will evaluate to true if value is not:

  • null
  • undefined
  • NaN
  • empty string ''
  • 0
  • false

typescript includes javascript rules.

like image 34
Ramazan Sağır Avatar answered Sep 21 '22 14:09

Ramazan Sağır