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
๐ŸŒ
W3Schools
w3schools.com โ€บ typescript โ€บ typescript_null.php
TypeScript Null & Undefined
TypeScript's inference system isn't perfect, there are times when it makes sense to ignore a value's possibility of being null or undefined. An easy way to do this is to use casting, but TypeScript also provides the ! operator as a convenient shortcut.
๐ŸŒ
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.
๐ŸŒ
TypeScript
typescriptlang.org โ€บ docs โ€บ handbook โ€บ release-notes โ€บ typescript-3-7.html
TypeScript: Documentation - TypeScript 3.7
In TypeScript 3.7, this is identified as a likely error: ... This check is a breaking change, but for that reason the checks are very conservative. This error is only issued in if conditions, and it is not issued on optional properties, if strictNullChecks is off, or if the function is later called within the body of the if: ... If you intended to test the function without calling it, you can correct the definition of it to include undefined/null, or use !!
Top answer
1 of 15
428

Yes. As of TypeScript 3.7 (released on November 5, 2019), this feature is supported and is called Optional Chaining:

At its core, optional chaining lets us write code where TypeScript can immediately stop running some expressions if we run into a null or undefined. The star of the show in optional chaining is the new ?. operator for optional property accesses.

Refer to the TypeScript 3.7 release notes for more details.


Prior to version 3.7, this was not supported in TypeScript, although it was requested as early as Issue #16 on the TypeScript repo (dating back to 2014).

As far as what to call this operator, there doesn't appear to be a consensus. In addition to "optional chaining" (which is also what it's called in JavaScript and Swift), there are a couple of other examples:

  • CoffeeScript refers to it as the existential operator (specifically, the "accessor variant" of the existential operator):

The accessor variant of the existential operator ?. can be used to soak up null references in a chain of properties. Use it instead of the dot accessor . in cases where the base value may be null or undefined.

  • C# calls this a null-conditional operator.

a null-conditional operator applies a member access, ?., or element access, ?[], operation to its operand only if that operand evaluates to non-null; otherwise, it returns null.

  • Kotlin refers to it as the safe call operator.

There are probably lots of other examples, too.

2 of 15
157

It is now possible, see answer of user "Donut".

Old answer: Standard JavaScript behaviour regarding boolean operators has something that may help. The boolean methods do not return true or false when comparing objects, but in case of OR the first value that is equal to true.

Not as nice as a single ?, but it works:

var thing = foo && foo.bar || null;

You can use as many && as you like:

var thing = foo && foo.bar && foo.bar.check && foo.bar.check.x || null;

Default values are also possible:

var name = person && person.name || "Unknown user";
๐ŸŒ
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.
๐ŸŒ
W3Schools
w3schools.io โ€บ javascript โ€บ es11-nullish-coalescing-operator
ES2020(ES11) - Javascript Nullish Coalescing Operator - w3schools
Nullish Coalescing was introduced in Typescript 3.7 language. This will be useful for checking the response from consuming API calls Assumed the API calls return response and the response nested structure as follows
๐ŸŒ
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 ...
Find elsewhere
๐ŸŒ
Marius Schulz
mariusschulz.com โ€บ blog โ€บ null-checking-for-expression-operands-in-typescript
Null-Checking for Expression Operands in TypeScript โ€” Marius Schulz
November 22, 2020 - With TypeScript 2.2, null checking is improved even further. TypeScript now flags expressions with nullable operands as compile-time errors.
๐ŸŒ
Upmostly
upmostly.com โ€บ home โ€บ typescript โ€บ how to detect null and undefined
How to Detect Null and Undefined in Your TypeScript Code - Upmostly
March 28, 2023 - You might notice Iโ€™ve used โ€œ===โ€ here, which is the strict equality operator. The difference here is that โ€œ===โ€ as a stricter operator, will specifically check for null or undefined. Letโ€™s take a look at this function, which uses the regular equality operator โ€œ==โ€ instead of the stricter variant:
๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ typescript โ€บ check for both null and undefined in typescript
How to Check for Both Null and Undefined in TypeScript | Delft Stack
February 2, 2024 - It is only possible to perform the strict check for the null using the == operator. In TypeScript, we can check for null and undefined simultaneously by following the juggling-check method.
Top answer
1 of 3
170

It's called the "Non-null assertion operator" and it tells the compiler that x.getY() is not null.

It's a new typescript 2.0 feature and you can read about it in the what's new page, here's what it says:

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. Specifically, the operation x! produces a value of the type of x with null and undefined excluded. Similar to type assertions of the forms x and x as T, the ! non-null assertion operator is simply removed in the emitted JavaScript code.

// Compiled with --strictNullChecks
function validateEntity(e?: Entity) {
    // Throw exception if e is null or invalid entity
}

function processEntity(e?: Entity) {
    validateEntity(e);
    let s = e!.name;  // Assert that e is non-null and access name
}

Edit

There's an issue for documenting this feature: Document non-null assertion operator (!)

2 of 3
45

Non-null assertion operator: !

  • You tells the TS compiler that the value of a variable is not null | undefined
  • Use it when you are in possession of knowledge that the TS compiler lacks.

Here is a trivial example of what it does:

let nullable1: null | number;
let nullable2: undefined | string;

let foo  = nullable1! // type foo: number
let fooz = nullable2! // type fooz: string

It basically removes null | undefined from the type


When do I use this?

Typescript is already pretty good at inferring types for example using typeguards:

let nullable: null | number | undefined;

if (nullable) {
    const foo = nullable; // ts can infer that foo: number, since if statements checks this
}

However sometimes we are in a scenario which looks like the following:

type Nullable = null | number | undefined;

let nullable: Nullable;

validate(nullable);

// Here we say to ts compiler:
// I, the programmer have checked this and foo is not null or undefined
const foo = nullable!;  // foo: number

function validate(arg: Nullable) {
    // normally usually more complex validation logic
    // but now for an example
    if (!arg) {
        throw Error('validation failed')
    }
}

My personal advice is to try to avoid this operator whenever possible. Let the compiler do the job of statically checking your code. However there are scenarios especially with vendor code where using this operator is unavoidable.

๐ŸŒ
Marius Schulz
mariusschulz.com โ€บ blog โ€บ nullish-coalescing-the-operator-in-typescript
Nullish Coalescing: The ?? Operator in TypeScript โ€” Marius Schulz
August 14, 2021 - That way, we can start using the ?? operator in our code today and still have the compiled code successfully parse and execute in older JavaScript engines. Let's look at the same simple ?? expression again: ... Assuming we're targeting "ES2019" or a lower language version, the TypeScript compiler will emit the following JavaScript code: value !== null && value !== void 0 ?
๐ŸŒ
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.
๐ŸŒ
TypeScript
typescriptlang.org โ€บ docs โ€บ handbook โ€บ advanced-types.html
TypeScript: Documentation - Advanced Types
TypeScript has two special types, null and undefined, that have the values null and undefined respectively. We mentioned these briefly in the Basic Types section. By default, the type checker considers null and undefined assignable to anything. Effectively, null and undefined are valid values ...
๐ŸŒ
Learn TypeScript
learntypescript.dev โ€บ 07 โ€บ l2-non-null-assertion-operator
Using the non-null assertion operator | Learn TypeScript
The non-null assertion operator is an exclamation mark (!), and this is placed after the variable or expression that we want to tell TypeScript isn't null or undefined. Update the return statement in code with the non-null assertion operator ...
๐ŸŒ
Omarileon
omarileon.me โ€บ blog โ€บ typescript-null-undefined
mari. | How to Detect Null and Undefined in Your TypeScript Code
February 27, 2024 - You might see it less often, but there is also a nullish-coalescing assignment operator. It looks like this: let foo = null; foo ??= 'foo'; foo ??= 'bar'; console.log(foo); // 'foo' It's just nullish-coalescing and assignment combined - if the value on the right is non-null, it will be assigned to the value on the left. TypeScript also provides a useful shortcut for checking if a property on an object might be null or undefined.