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"

Answer from Fenton on Stack Overflow
🌐
TypeScript
typescriptlang.org › docs › handbook › release-notes › typescript-2-0.html
TypeScript: Documentation - TypeScript 2.0
A property access or a function call produces a compile-time error if the object or function is of a type that includes null or undefined. However, type guards are extended to support non-null and non-undefined checks. ... Non-null and non-undefined type guards may use the ==, !=, ===, or !== operator to compare to null or undefined, as in x != null or x === undefined.
🌐
W3Schools
w3schools.com › typescript › typescript_null.php
TypeScript Null & Undefined
Nullish coalescing is another JavaScript feature that also works well with TypeScript's null handling. It allows writing expressions that have a fallback specifically when dealing with null or undefined. This is useful when other falsy values can occur in the expression but are still valid. It can be used with the ?? operator in an expression, similar to using the && operator.
Top answer
1 of 2
6

This is a proposed feature in TypeScript, under the legendary Issue #16

It won't be introduced into TypeScript until the ECMAScript spec for this feature is firm as there is a desire for the TypeScript implementation to follow that specification - so you'll get it early, but not massively early in this case.

It is referred to as any of the following:

  • Null Propagation Operator
  • Existential Operator
  • Null Coalesce Operator
2 of 2
5

Update in 2020: The nullish-coalescing operator mentioned below is now through the process and in ES2020, as is the optional chaining operator that lets you do:

let postal_code = address?.postal_code;
// −−−−−−−−−−−−−−−−−−−−−−^

With optional chaining, if address is null or undefined, postal_code will get undefined as its value. But if address is neither null nor undefined, postal_code will get the value of address.postal_code.


JavaScript doesn't have a null-coalescing operator (nor does TypeScript, which mostly limits itself to adding a type layer and adopting features that are reasonably far along the path to making it into JavaScript). There is a proposal for a JavaScript null-coalescing operator, but it's only at Stage 1 of the process.

Using the && idiom you've described is a fairly common approach:

let postal_code = address && address.postal_code;

If address is null (or any other falsy¹ value), postal_code will be that same value; otherwise, it will be whatever value address.postal_code was.


¹ The falsy values are 0, "", NaN, null, undefined, and of course false.

🌐
TutorialsPoint
tutorialspoint.com › javascript-typescript-object-null-check
JavaScript/ Typescript object null check?
To check a variable is null or not in typescript we can use typeof or "===" operator.
🌐
Reddit
reddit.com › r/reactjs › is null checking necessary in typescript for runtime safety?
r/reactjs on Reddit: Is Null Checking Necessary in TypeScript for Runtime Safety?
August 13, 2024 -

TypeScript types are only enforced at compile time and do not exist at runtime. Given this, if I define a TypeScript function that accepts a string parameter, is it necessary to perform null checks? This question arises because if the API returns null, it could lead to runtime errors.

Consider the following code snippet:

const capitalise = (val: string) => {
   // Question: Is this check redundant due to TypeScript's type checking?
   if (!val) {
      return '';
   }

   return val.toUpperCase();
};

// Assume 'name' is fetched from an API or another source that could return null
const name: string = /* fetch from API or another source */;

capitalise(name);

What are the best practices in such scenarios to ensure runtime safety in TypeScript applications?

🌐
Bobby Hadz
bobbyhadz.com › blog › react-null-or-undefined-check
Check if a Variable is Null or Undefined in React | bobbyhadz
To check if a variable is null or undefined in React, use the || (or) operator to check if either of the two conditions is met.
🌐
Sentry
sentry.io › sentry answers › react › how to fix the forbidden non-null assertion in typescript and react?
How to fix the forbidden non-null assertion in TypeScript and React? | Sentry
To use it, add the ! symbol after an expression like in the console log example above. When your TypeScript configuration is set to do "strictNullChecks", use the non-null assertion operator to bypass the null and undefined type checks.
Find elsewhere
🌐
Ohansemmanuel
blog.ohansemmanuel.com › in-typescript-what-is-the-exclamation-mark-or-bang-operator
In Typescript, what is the ! (exclamation mark / bang) operator?
July 7, 2022 - In the example above (for those who do not write React), in the React mental model, ref.current will certainly be available at the time the button is clicked by the user. The ref object is set soon after the UI elements are rendered. Typescript does not know this, and you may be forced to use the non-null assertion operator here.
🌐
Rampatra
blog.rampatra.com › null-vs-undefined-in-typescript-or-javascript-how-to-check-for-both-at-once
!== null vs !== undefined in Typescript or Javascript, how to check for both at once?
(nullish coalescing operator) and || (logical OR operator) are both used to provide default values, but they behave differently in terms of the conditions under which they return the right-hand operand. ... question typescript react September 28, 2024 How to add a custom element to a ...
🌐
Medium
medium.com › @bobjunior542 › how-to-use-the-operator-in-typescript-for-cleaner-more-efficient-code-7fd528f8f8b1
How to Use the ‘!’ Operator in TypeScript for Cleaner, More Efficient Code | by Bob Junior | Medium
April 25, 2023 - If the age property is null or undefined, we are using a type guard to narrow down the type of the user object. ... The ! operator is a powerful tool in TypeScript that can help you avoid compilation errors when working with nullable types.
🌐
Medium
medium.com › @tar.viturawong › a-note-on-typescript-non-null-assertion-operator-bad8fbe62bba
A note on TypeScript non-null assertion operator | by Tar Viturawong | Medium
March 25, 2019 - If using the new style context, re-declare this in your class to be theReact.ContextType of your static contextType.* static contextType = MyContext * context!: React.ContextType<typeof MyContext> *@deprecated — if used without a type annotation, or without static contextType ... It turned out that this operator ! placed after an expression is TypeScript’s non-null assertion operator.
🌐
GitBook
basarat.gitbook.io › typescript › intro › strictnullchecks
strictNullChecks | TypeScript Deep Dive
But in strict null checking mode, this error will be caught at compile time: ... getMember() .then(member: Member => { const stringifyAge = member.age.toString() // Object is possibly 'undefined' }) A new ! post-fix expression operator may be used to assert that its operand is non-null and non-undefined in contexts where the type checker is unable to conclude that fact.
🌐
Reddit
reddit.com › r/typescript › strict null checks in ternary operators?
r/typescript on Reddit: Strict null checks in ternary operators?
March 6, 2019 -

Hi, I have a question that I can't seem to find an answer to, but I assume there is an easy fix for?

I have the following code in a .tsx file (as part of the render method):

<div>
    <TableHead />
    {this.state.scoreList === null ? <CircularProgress /> :
        this.state.scoreList.map((row: IScore) => {
            <TableRow>
                <TableCell>{row.name}</TableCell>
                <TableCell>{row.likes}</TableCell>
                <TableCell>{row.likesSum}</TableCell>
                <TableCell>{row.lps}</TableCell>
            </TableRow>
        })
    }
</div>

This throws Type error: Object is possibly 'null'. TS2531 on the 4th line of the snippet, even though - logically - it can't be null because I have caught that with the ternary operator. Is there a way to tell TS this without globally disabling strictNullChecks?

Edit: Thanks all, you guys and gals are amazing, I think I learned like 10 new things just by posting this question, very much appreciated! Sincere props (see what I did there?) to all of you!

🌐
Coding Beauty
codingbeautydev.com › home › posts › how to check if a variable is null or undefined in react
How to Check if a Variable is Null or Undefined in React
October 4, 2023 - To check if a variable in null or undefined in React, use the || operator to check if the variable is equal to null or equal to undefined.
🌐
GeeksforGeeks
geeksforgeeks.org › typescript › how-to-check-null-and-undefined-in-typescript
How to check null and undefined in TypeScript ? - GeeksforGeeks
July 23, 2025 - Example: Below is an example demonstrating the use of optional chaining and nullish coalescing operators to check for null or undefined values. We declare variables that can be either undefined, null, or assigned a value. let undefinedVar: string | undefined; let nullVar: string | null = null; let assignedVar: string | null | undefined = "Hello, World!"; ... let undefinedVar: string | undefined; let nullVar: string | null = null; let assignedVar: string | null | undefined = "Hello, World!"; const checkUndefinedVar = undefinedVar ??
🌐
Reddit
reddit.com › r/typescript › how to reason about possibly null values during development?
r/typescript on Reddit: How to reason about possibly null values during development?
January 13, 2024 -

I'm coming at this as a typescript beginner and haven't had a deep dive into the docs. So apologies if I'm missing something very obvious.

During development specifically, I feel like I'm adding null checks to my code too early to make TS happy, and this makes it harder to reason about my code. It'll go like this:

  • I perform an operation on a variable that can be null sometimes

  • TS alerts me to this, so I add a null check with an elvis operator/ternary/if

  • The variable is in fact null in an unexpected scenario, so I have a functional error in my app

  • Because I'm null-checking to shush the compiler, I don't immediately know where the bad value originates from and have to dig around for it

I can imagine this getting very annoying once I'm several layers of calls deep. So, how do I think about this? Should I be checking for null values differently? Should I always be doing something in the control flow to indicate an unexpected null was passed? Should I be throwing more?

Advice welcome. Thanks!

🌐
Honlsoft
honlsoft.com › blog › 2021-07-20-typescript-tips-null-coalescing
Typescript Tips: null(and undefined) Checking | Honlsoft
Thankfully, in Typescript, there are several shorthand ways to deal with nulls. The Elvis operator is a shorthand way to check for null or undefined without requiring a separate if statement.
🌐
Bobby Hadz
bobbyhadz.com › blog › typescript-check-if-null
How to correctly check for Null in TypeScript | bobbyhadz
The first if statement uses the loose equals (==) operator instead of strict equals (===), and checks if the variable is equal to null or undefined. This checks for both null and undefined because when using loose equals (==), null is equal ...