ChatGPT解决这个技术问题 Extra ChatGPT

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?

Since TypeScript is strongly-typed I couldn't find this in it's docs and I have doubts about it...
Recommend to read up on the latest non-nullable types , this is Typescript 2 , but already in beta as of today. [Non-nullable types #7140] (github.com/Microsoft/TypeScript/pull/7140)
TypeScript has no dedicated functions to do anything. It's a typing system and a transpiler, not a library.
As you say it is bad to just check if () {} since that will also be true for 0.

F
Fenton

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"


What is "juggling-check"?
@akapelko it is where the type is juggled (i.e. "can we make this type a boolean"). So an empty string is treated as a boolean false, for example. A common bug when juggling is: "false" == false a non-empty string like "false" evaluates to true.
This is due to JS's 'type coercion'.
@JonGunter that would be true of truthy/falsey if(x) style checks, but not if(x == null), which only catches null and undefined. Check it using var c: number = 0; check(c, 'b'); it is not "nully", null, or undefined.
@developer - not quite, as if (!x) would treat (for example) the number 0 and the string '' as null, whereas if (x == null) would not.
k
kingdaro
if( value ) {
}

will evaluate to true if value is not:

null

undefined

NaN

empty string ''

0

false

typescript includes javascript rules.


What if value is of boolean type?
can you combine two variables eg. if(value1 && value2) to check if both of them are undefined ?
@RamazanSağır yeah thanks I know that, but the fact is 0 value is something valid that I can have, the only check I want to do is that the variable is neither null or undefined. I have read that I can do it by using val != null (the != instead of !== also checks undefined value)
This solution will not work if the tslint rule - "strict-boolean-expressions" is enabled.
It will evaluate false if value us falsy, as simple as this.
F
Fateh Mohamed

In TypeScript 3.7 we have now Optional chaining and Nullish Coalescing to check null and undefined in the same time, example:

let x = foo?.bar.baz();

this code will check if foo is defined otherwise it will return undefined

old way :

if(foo != null && foo != undefined) {
   x = foo.bar.baz();
} 

this:

let x = (foo === null || foo === undefined) ? undefined : foo.bar();

if (foo && foo.bar && foo.bar.baz) { // ... }

With optional chaining will be:

let x = foo?.bar();

if (foo?.bar?.baz) { // ... }

another new feature is Nullish Coalescing, example:

let x = foo ?? bar(); // return foo if it's not null or undefined otherwise calculate bar

old way:

let x = (foo !== null && foo !== undefined) ?
foo :
bar();

https://i.stack.imgur.com/OPBH5.png


This should be the accepted answer now. Typescript 3.7 also supports "Nullish Coalescing". var foo = possibleUndefinedOrNull ?? fallbackValueIfFirstValueIsUndefinedOrNull; Here is the documentation: typescriptlang.org/docs/handbook/release-notes/…
Optional chaining and Nullish Coalescing are great but in case of a single if stmt like if (context != null) word.ctx = context; one still has to resort to the old juggling-check as described in the upvoted comment stackoverflow.com/a/28984306/407986
Yes, for almost scenarios, we could we Optional chaining , e.g. if (foo?.bar?.baz) typescriptlang.org/docs/handbook/release-notes/…
Nullish Coalescing seems not supported in typescript 4.5.4. Is it deprecated?
Tried const bar = foo ?? 'undefined'; Per Nullish Coalescing, when foo is null or empty, bar should store 'undefined', but I am getting ''. Is it supported in typescript 4.5.4? Via ternary operator it works const bar = foo ? foo : 'undefined';
b
basarat

Does TypeScript has dedicated function or syntax sugar for this

TypeScript fully understands the JavaScript version which is something == null.

TypeScript will correctly rule out both null and undefined with such checks.

More

https://basarat.gitbook.io/typescript/recap/null-undefined


I like doing two equals myVar == null. Just another option.
== null is the correct way to test for null & undefined. !!something is a useless coercion in a conditional in JS (just use something). !!something will also coerce 0 and '' to false, which is not what you want to do if you are looking for null/undefined.
J
Juangui Jordán

I did different tests on the typescript playground:

http://www.typescriptlang.org/play/

let a;
let b = null;
let c = "";
var output = "";

if (a == null) output += "a is null or undefined\n";
if (b == null) output += "b is null or undefined\n";
if (c == null) output += "c is null or undefined\n";
if (a != null) output += "a is defined\n";
if (b != null) output += "b is defined\n";
if (c != null) output += "c is defined\n";
if (a) output += "a is defined (2nd method)\n";
if (b) output += "b is defined (2nd method)\n";
if (c) output += "c is defined (2nd method)\n";

console.log(output);

gives:

a is null or undefined
b is null or undefined
c is defined

so:

checking if (a == null) is right to know if a is null or undefined

checking if (a != null) is right to know if a is defined

checking if (a) is wrong to know if a is defined


Why would you use the TypeScript playground for this? Nothing here has anything to do with TypeScript.
Because the question was related to Typescript, I was trying to test different proposed solutions against the Typescript transpiler.
The TS transpiler would not transform any of this code at all.
a
avi.elkharrat

You may want to try

if(!!someValue)

with !!.

Explanation

The first ! will turn your expression into a boolean value.

Then !someValue is true if someValue is falsy and false if someValue is truthy. This might be confusing.

By adding another !, the expression is now true if someValue is truthy and false if someValue is falsy, which is much easier to manage.

Discussion

Now, why do I bother myself with if (!!someValue) when something like if (someValue) would have give me the same result?

Because !!someValue is precisely a boolean expression, whereas someValue could be absolutely anything. This kind of expression will now alow to write functions (and God we need those) like:

isSomeValueDefined(): boolean {
  return !!someValue
}

instead of:

isSomeValueDefined(): boolean {
  if(someValue) {
    return true
  }
  return false
}

I hope it helps.


so, if someValue is 'false'(with string type), then !!someValue is false(boolean type)?
I guess you may say so.This technic is precisely used to avoid having this kind of confusion. I hope you like it!
but what confused me is !!'false' equals true. Just because of this case, i can not use this technic.
!!'false' is in deed true because 'false' is a valid string
so this technic can not cover this case, or is there a workaround solution?
A
Ahmed Kamal

I think this answer needs an update, check the edit history for the old answer.

Basically, you have three deferent cases null, undefined, and undeclared, see the snippet below.

// bad-file.ts
console.log(message)

You'll get an error says that variable message is undefined (aka undeclared), of course, the Typescript compiler shouldn't let you do that but REALLY nothing can prevent you.

// evil-file.ts
// @ts-gnore
console.log(message)

The compiler will be happy to just compile the code above. So, if you're sure that all variables are declared you can simply do that

if ( message != null ) {
    // do something with the message
}

the code above will check for null and undefined, BUT in case the message variable may be undeclared (for safety), you may consider the following code

if ( typeof(message) !== 'undefined' && message !== null ) {
    // message variable is more than safe to be used.
}

Note: the order here typeof(message) !== 'undefined' && message !== null is very important you have to check for the undefined state first atherwise it will be just the same as message != null, thanks @Jaider.


M. Kamal if something = 0, your verification with !something will give you problems.
@arturios can you please give me an example!!
@arturios But 0 is already a falsy value in JavaScript !! so what is the point here?
@Al-un nope, see it in action here
the updated version is wrong. The first thing to check should be undefined... like: if(typeof something !== 'undefined' && something !== null){...}
M
Maxim Pyshko

For Typescript 2.x.x you should do it in a following way(using type guard):

tl;dr

function isDefined<T>(value: T | undefined | null): value is T {
  return <T>value !== undefined && <T>value !== null;
}

Why?

In this way isDefined() will respect variable's type and the following code would know take this check in account.

Example 1 - basic check:

function getFoo(foo: string): void { 
  //
}

function getBar(bar: string| undefined) {   
  getFoo(bar); //ERROR: "bar" can be undefined
  if (isDefined(bar)) {
    getFoo(bar); // Ok now, typescript knows that "bar' is defined
  }
}

Example 2 - types respect:

function getFoo(foo: string): void { 
  //
}

function getBar(bar: number | undefined) {
  getFoo(bar); // ERROR: "number | undefined" is not assignable to "string"
  if (isDefined(bar)) {
    getFoo(bar); // ERROR: "number" is not assignable to "string", but it's ok - we know it's number
  }
}

I wish they added this as an util function.
Note that the check for nullish should be defined like this: function isNullish<T>(value: T | undefined | null): value is undefined | null { return <T>value === undefined || <T>value === null; }
@KfirDadosh is right, isNullish should be used instead, (or call it isNotDefined if you like). The problem with the original code is if the type parameter T is null or undefined, then the original code will return the opposite of the correct answer.
This should be the accepted answer in 2022
a
artemitSoft
if(data){}

it's mean !data

null

undefined

false

....


And if data is of boolean type?
can you combine two variables eg. if(value1 && value2) to check if both of them are undefined ?
@ianstigator A boolean can be evaluated as true or false only. If you have a boolean with a null assignation or an undefined value, in both cases the value will be evaluated as false.
d
danilo

SIMPLE ANSWER

to evaluate if value is null,undefined,0,false,"",NaN:

if ( value )
or
if ( !!value )

for negative conditional:

if ( !value )

to test only null or undefined:

if ( value == null )

MORE DETAILED ANSWER

1- It will evaluate to true if value is not: null, undefined, NaN, empty string '', 0, false
If the value is null,undefined,NaN,empty string,0, or false, will go to the else condition.

if ( value ) {
  console.log('value is something different from 0, "", false, NaN, null, undefined');
} else {
  console.log('value is 0, "", false, NaN, null or undefined');
}
if ( !!value ) {
  console.log('value is something different from 0, "", false, NaN, null, undefined');
} else {
  console.log('value is 0, "", false, NaN, null or undefined');
}

2- If you want a negative condition, then you'll need to use:

if ( !value ) {
  console.log('value is 0, "", false, NaN, null or undefined');
} else {
  console.log('value is something different from 0, "", false, NaN, null, undefined');
}

3- It will evaluate if value is null or undefined

if ( value == null ) {
  console.log('is null or undefined');
} else {
  console.log('it isnt null neither undefined');
}

4- Using a boolean conditional doesn't work.
It will NOT evaluate to true neither to false if value is null, undefined, 0, empty string, NaN
Both conditions will always go to the else condition.
With the exception if value is a boolean variable.

if ( value==true ) {
} else { 
}
if ( value==false ) {
} else { 
}

Do you mean less concise?
K
KBeDev

UPDATE (Sept 4, 2020)

You can now use the ?? operator to validate null and undefined "values" and set a default value. For example:

const foo = null;
const bar = foo ?? 'exampleValue';
console.log(bar); // This will print 'exampleValue' due to the value condition of the foo constant, in this case, a null value

As a verbose way, if you want to compare null and undefined values ONLY, use the following example code for reference:

const incomingValue : string = undefined;
const somethingToCompare : string = incomingValue; // If the line above is not declared, TypeScript will return an excepion

if (somethingToCompare == (undefined || null)) {
  console.log(`Incoming value is: ${somethingToCompare}`);
}

If incomingValue is not declared, TypeScript should return an exception. If this is declared but not defined, the console.log() will return "Incoming value is: undefined". Note we are not using the strict equals operator.

The "correct" way (check the other answers for details), if the incomingValue is not a boolean type, just evaluate if its value is true, this will be evaluated according to the constant/variable type. A true string have to be defined explicitly as string using the = '' assignation. If not, it will be evaluated as false. Let's check this case using the same context:

const incomingValue : string = undefined;
const somethingToCompare0 : string = 'Trumpet';
const somethingToCompare1 : string = incomingValue;

if (somethingToCompare0) {
  console.log(`somethingToCompare0 is: ${somethingToCompare0}`); // Will return "somethingToCompare0 is: Trumpet"
}

// Now, we will evaluate the second constant
if (somethingToCompare1) {
  console.log(`somethingToCompare1 is: ${somethingToCompare1}`); // Launched if incomingValue is defined
} else {
  console.log(`somethingToCompare1 is: ${somethingToCompare1}`); // Launched if incomingValue is undefined. Will return "somethingToCompare1 is: undefined"
}

somethingToCompare == (undefined || null). (undefined || null) resolves to null, so it's a loose comparison between somethingToCompare and null
@carlosvini Sure, the point of the comparison is to be verbose and provide a code for reference. That's the reason of the non-strict equals comparison. The purpose of the answer is to be clear and explicative. I'll edit the text to avoid confusion
I don't understand what you mean. The code is not verbose or explicit, it is confusing at best and plain wrong at worst. The code a == (b || c) is the not the same as a == b || a == c, instead it will evaluate b || c (in this case to c since b is falsy in your example) and then compare that against a.
佚名

If you are using TypeScript, it is a better approach to let the compiler check for nulls and undefineds (or the possibility thereof), rather than checking for them at run-time. (If you do want to check at run-time, then as many answers indicate, just use value == null).

Use the compile option strictNullChecks to tell the compiler to choke on possible null or undefined values. If you set this option, and then there is a situation where you do want to allow null and undefined, you can define the type as Type | null | undefined.


G
Graeme Wicksted

If you want to pass tslint without setting strict-boolean-expressions to allow-null-union or allow-undefined-union, you need to use isNullOrUndefined from node's util module or roll your own:

// tslint:disable:no-null-keyword
export const isNullOrUndefined =
  <T>(obj: T | null | undefined): obj is null | undefined => {
    return typeof obj === "undefined" || obj === null;
  };
// tslint:enable:no-null-keyword

Not exactly syntactic sugar but useful when your tslint rules are strict.


R
Ruthi

The simplest way is to use:

import { isNullOrUndefined } from 'util';

and than:

if (!isNullOrUndefined(foo))


Works great here
From the function docs: deprecated since v4.0.0 - use value === null || value === undefined instead.
@Aleksei that's ironic
S
Shahid Manzoor Bhat

Late to join this thread but I find this JavaScript hack very handy in checking whether a value is undefined

 if(typeof(something) === 'undefined'){
   // Yes this is undefined
 }

F
Freewalker

We use a helper hasValue that both checks for nulls/undefined and ensures via TypeScript that unnecessary checks are not performed. (The latter is similar to how TS would complain about if ("a" === undefined), since it is always false).

Using this consistently is always safe, unlike !val which matches empty strings, zero, etc. It also avoid the use of fuzzy == matching which is almost always a bad practice - no need to introduce an exception.



type NullPart<T> = T & (null | undefined);

// Ensures unnecessary checks aren't performed - only a valid call if 
// value could be nullable *and* could be non-nullable
type MustBeAmbiguouslyNullable<T> = NullPart<T> extends never
  ? never
  : NonNullable<T> extends never
  ? never
  : T;

export function hasValue<T>(
  value: MustBeAmbiguouslyNullable<T>,
): value is NonNullable<MustBeAmbiguouslyNullable<T>> {
  return (value as unknown) !== undefined && (value as unknown) !== null;
}

export function hasValueFn<T, A>(
  value: MustBeAmbiguouslyNullable<T>,
  thenFn: (value: NonNullable<T>) => A,
): A | undefined {
  // Undefined matches .? syntax result
  return hasValue(value) ? thenFn(value) : undefined;
}



A
Ali Qamsari

May be to late! but you can use ?? operator in typescript. see https://mariusschulz.com/blog/nullish-coalescing-the-operator-in-typescript


J
Julian

you can use

if(x === undefined)

B
Ben Croughs

All,

The answer with the most votes, does not really work if you are working with an object. In that case, if a property is not present, the check will not work. And that was the issue in our case: see this sample:

var x =
{ name: "Homer", LastName: "Simpson" };

var y =
{ name: "Marge"} ;

var z =
{ name: "Bart" , LastName: undefined} ;

var a =
{ name: "Lisa" , LastName: ""} ;

var hasLastNameX = x.LastName != null;
var hasLastNameY = y.LastName != null;
var hasLastNameZ = z.LastName != null;
var hasLastNameA = a.LastName != null;



alert (hasLastNameX + ' ' + hasLastNameY + ' ' + hasLastNameZ + ' ' + hasLastNameA);

var hasLastNameXX = x.LastName !== null;
var hasLastNameYY = y.LastName !== null;
var hasLastNameZZ = z.LastName !== null;
var hasLastNameAA = a.LastName !== null;

alert (hasLastNameXX + ' ' + hasLastNameYY + ' ' + hasLastNameZZ + ' ' + hasLastNameAA);

Outcome:

true , false, false , true (in case of !=)
true , true, true, true (in case of !==) => so in this sample not the correct answer

plunkr link: https://plnkr.co/edit/BJpVHD95FhKlpHp1skUE


This is not good test. None of those values are strictly null. Try this: plnkr.co/edit/NfiVnQNes1p8PvXd1fCG?p=preview
H
Harry Stylesheet

A faster and shorter notation for null checks can be:

value == null ? "UNDEFINED" : value

This line is equivalent to:

if(value == null) {
       console.log("UNDEFINED")
} else {
    console.log(value)
}

Especially when you have a lot of null check it is a nice short notation.


T
T04435

I had this issue and some of the answer work just fine for JS but not for TS here is the reason.

//JS
let couldBeNullOrUndefined;
if(couldBeNullOrUndefined == null) {
  console.log('null OR undefined', couldBeNullOrUndefined);
} else {
  console.log('Has some value', couldBeNullOrUndefined);
}

That is all good as JS has no Types

//TS
let couldBeNullOrUndefined?: string | null; // THIS NEEDS TO BE TYPED AS undefined || null || Type(string)

if(couldBeNullOrUndefined === null) { // TS should always use strict-check
  console.log('null OR undefined', couldBeNullOrUndefined);
} else {
  console.log('Has some value', couldBeNullOrUndefined);
}

In TS if the variable wasn't defined with null when you try to check for that null the tslint | compiler will complain.

//tslint.json
...
"triple-equals":[true],
...
 let couldBeNullOrUndefined?: string; // to fix it add | null

 Types of property 'couldBeNullOrUndefined' are incompatible.
      Type 'string | null' is not assignable to type 'string | undefined'.
        Type 'null' is not assignable to type 'string | undefined'.

N
Neo

Usually I do the juggling-check as Fenton already discussed. To make it more readable, you can use isNil from ramda.

import * as isNil from 'ramda/src/isNil';

totalAmount = isNil(totalAmount ) ? 0 : totalAmount ;

R
Rusty Rob

careful if you're using local storage, you can end up with the string undefined rather than the value undefined:

localStorage.setItem('mykey',JSON.stringify(undefined));
localStorage.getItem('mykey') === "undefined"
true

People may find this useful: https://github.com/angular/components/blob/master/src/cdk/coercion/boolean-property.spec.ts

/**
 * @license
 * Copyright Google LLC All Rights Reserved.
 *
 * Use of this source code is governed by an MIT-style license that can be
 * found in the LICENSE file at https://angular.io/license
 */

/** Coerces a data-bound value (typically a string) to a boolean. */
export function coerceBooleanProperty(value: any): boolean {
  return value != null && `${value}` !== 'false';
}

import {coerceBooleanProperty} from './boolean-property';

describe('coerceBooleanProperty', () => {

  it('should coerce undefined to false', () => {
    expect(coerceBooleanProperty(undefined)).toBe(false);
  });

  it('should coerce null to false', () => {
    expect(coerceBooleanProperty(null)).toBe(false);
  });

  it('should coerce the empty string to true', () => {
    expect(coerceBooleanProperty('')).toBe(true);
  });

  it('should coerce zero to true', () => {
    expect(coerceBooleanProperty(0)).toBe(true);
  });

  it('should coerce the string "false" to false', () => {
    expect(coerceBooleanProperty('false')).toBe(false);
  });

  it('should coerce the boolean false to false', () => {
    expect(coerceBooleanProperty(false)).toBe(false);
  });

  it('should coerce the boolean true to true', () => {
    expect(coerceBooleanProperty(true)).toBe(true);
  });

  it('should coerce the string "true" to true', () => {
    expect(coerceBooleanProperty('true')).toBe(true);
  });

  it('should coerce an arbitrary string to true', () => {
    expect(coerceBooleanProperty('pink')).toBe(true);
  });

  it('should coerce an object to true', () => {
    expect(coerceBooleanProperty({})).toBe(true);
  });

  it('should coerce an array to true', () => {
    expect(coerceBooleanProperty([])).toBe(true);
  });
});

D
Daniel

You can do this easily with a ternary operator and the new nullish coalesce operator.

First: check to see if it is true using the ternary. If so return false so the if statement does not run.

Second: because you now know the value is falsey, you can use the nullish coalesce operator to return true if it is nullish. Since it will return itself for any other value, if it is not nullish it will fail the if statement correctly.

let x = true; console.log("starting tests") if (x?false:x ?? true){ console.log(x,"is nullish") } x = false if (x?false:x ?? true){ console.log(x,"is nullish") } x = 0; if (x?false:x ?? true){ console.log(x,"is nullish") } x=1; if (x?false:x ?? true){ console.log(x,"is nullish") } x=""; if (x?false:x ?? true){ console.log(x,"is nullish") } x="hello world"; if (x?false:x ?? true){ console.log(x,"is nullish") } x=null; if (x?false:x ?? true){ console.log(x,"is nullish") } x=undefined; if (x?false:x ?? true){ console.log(x,"is nullish") }


7
7e2e63de

Since TypeScript is a typed superset of ES6 JavaScript. And lodash are a library of javascript.

Using lodash to checks if value is null or undefined can be done using _.isNil().

_.isNil(value)

Arguments

value (*): The value to check.

Returns

(boolean): Returns true if value is nullish, else false.

Example

_.isNil(null);
// => true

_.isNil(void 0);
// => true

_.isNil(NaN);
// => false

Link

Lodash Docs


Why this method are -2 ? Lodash is not good with type script ?
d
danilo

Try this, use !! operator along with the variable.

let check;
if (!!check) {
  console.log('check is not null or not undefined');
} else {
  console.log('check is  null or  undefined');
}

It will be very useful in Angular.
To check undefined and null of any variable.


This will return false for other values such as 0, false and empty strings
R
Rusty Rob

I always write it like this:

var foo:string;

if(!foo){
   foo="something";    
}

This will work fine and I think it's very readable.


Wouldn't work for numbers because 0 also passes the !foo test.
Does not work for booleans either, where undefined is different than false. This is very common with optional boolean function parameters, where you should use the common JavaScript approach: function fn(flag?: boolean) { if (typeof flag === "undefined") flag = true; /* set default value */ }
Seems to work ok for booleans: var isTrue; if(isTrue)//skips, if(!isTrue)// enters if(isTrue === undefined)//enters. Also tried it in typescript with var isTrue:boolean which was undefined, and the same if checks. @Gingi, is there something different about what you tried and what I tried?