At time of writing, TypeScript does not support the optional chaining operator. See discussion on the TypeScript issue tracker: https://github.com/Microsoft/TypeScript/issues/16

As a warning, the semantics of this operator are still very much in flux, which is why TypeScript hasn't added it yet. Code written today against the Babel plugin may change behavior in the future without warning, leading to difficult bugs. I generally recommend people to not start using syntax whose behavior hasn't been well-defined yet.

Answer from Ryan Cavanaugh on Stack Overflow
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Operators › Optional_chaining
Optional chaining (?.) - JavaScript | MDN
The optional chaining (?.) operator accesses an object's property or calls a function. If the object accessed or function called using this operator is undefined or null, the expression short circuits and evaluates to undefined instead of throwing an error.
🌐
TypeScript
typescriptlang.org › docs › handbook › release-notes › typescript-3-7.html
TypeScript: Documentation - TypeScript 3.7
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.
🌐
TypeScript
typescriptlang.org › play › 3-7 › syntax-and-messaging › optional-chaining.ts
TypeScript: Playground Example - Optional Chaining
const artistBio = album?.artist?.bio; ... values (e.g. an empty string, 0, NaN, and, well, false). Optional chaining will only take null or undefined as a signal to stop and return an undefined. Optional Element Access Property access is via the . operator, the optional chaining ...
Top answer
1 of 3
20

At time of writing, TypeScript does not support the optional chaining operator. See discussion on the TypeScript issue tracker: https://github.com/Microsoft/TypeScript/issues/16

As a warning, the semantics of this operator are still very much in flux, which is why TypeScript hasn't added it yet. Code written today against the Babel plugin may change behavior in the future without warning, leading to difficult bugs. I generally recommend people to not start using syntax whose behavior hasn't been well-defined yet.

2 of 3
12

Update Oct 15, 2019

Support now exists in [email protected]

Say thanks to https://stackoverflow.com/a/58221278/6502003 for the update!


Although TypeScript and the community are in favor of this operator, until TC39 solidifies the current proposal (which at the time of this writing is at stage 1) we will have to use alternatives.

There is one alternative which gets close to optional chaining without sacrificing dev tooling: https://github.com/rimeto/ts-optchain

This article chronicles what the creators were able to achieve in trying to mirror the native chaining operator:

  1. Use a syntax that closely mirrors chained property access
  2. Offer a concise expression of a default value when traversal fails
  3. Enable IDE code-completion tools and compile-time path validation

In practice it looks like this:

import { oc } from 'ts-optchain';

// Each of the following pairs are equivalent in result.
oc(x).a();
x && x.a;

oc(x).b.d('Default');
x && x.b && x.b.d || 'Default';

oc(x).c[100].u.v(1234);
x && x.c && x.c[100] && x.c[100].u && x.c[100].u.v || 1234;

Keep in mind that alternatives like this one will likely be unnecessary once the proposal is adopted by TypeScript.

Also, a big thanks to Ryan Cavanaugh for all the work you are doing in advocating this operator to TC39!

🌐
LogRocket
blog.logrocket.com › home › optional chaining and nullish coalescing in typescript
Optional chaining and nullish coalescing in TypeScript - LogRocket Blog
June 4, 2024 - In TypeScript, optional chaining is defined as the ability to immediately stop running an expression if a part of it evaluates to either null or undefined. It was introduced in TypeScript 3.7 with the ?. operator.
🌐
JavaScript.info
javascript.info › tutorial › the javascript language › objects: the basics
Optional chaining '?.'
There’s a little better way to write it, using the && operator: let user = {}; // user has no address alert( user.address && user.address.street && user.address.street.name ); // undefined (no error) AND’ing the whole path to the property ensures that all components exist (if not, the evaluation stops), but also isnt ideal. As you can see, property names are still duplicated in the code. E.g. in the code above, user.address appears three times. That’s why the optional chaining ?.
🌐
egghead.io
egghead.io › lessons › typescript-use-the-optional-chaining-operator-in-typescript
Use the Optional Chaining Operator in TypeScript | egghead.io
This lesson introduces the ?. operator which is known as optional chaining. We're going to look at how we can use ?. to safely descend into an object with properties which potentially hold the values null or undefined.
Published   February 17, 2021
🌐
Marius Schulz
mariusschulz.com › blog › optional-chaining-the-operator-in-typescript
Optional Chaining: The ?. Operator in TypeScript — Marius Schulz
September 11, 2021 - TypeScript 3.7 added support for ... use this operator to descend into an object whose properties potentially hold the values null or undefined without writing any null checks for intermediate properties....
Find elsewhere
🌐
Scaler
scaler.com › home › topics › typescript › optional chaining and nullish coalescing in typescript
Optional Chaining and Nullish Coalescing in TypeScript - Scaler Topics
May 4, 2023 - To access options, we may utilize the ?. operator. formatting. at each level of this property chain, indent with checks for null values : Optional chaining in typescript is described in the ECMAScript standard as follows :
Top answer
1 of 2
16

Optional chaining ?. is safer to use than non-null assertions !.

Consider the following interface:

interface Foo {
    bar?: {
        baz: string;
    }
}

The bar property is optional. If it doesn't exist it will be undefined when you read it. If it does exist it will have a baz property of type string. If you just try to access the baz property without making sure that bar is defined, you'll get a compiler error warning you about a possible runtime error:

function oops(foo: Foo) {
    console.log(foo.bar.baz.toUpperCase()); // compiler error
    // -------> ~~~~~~~
    // Object is possibly undefined
}

Optional chaining has actual effects at runtime and short-circuits to an undefined value if the property you're trying to access does not exist. If you don't know for sure that a property exists, optional chaining can protect you from some runtime errors. The TypeScript compiler does not complain with the following code because it knows that what you are doing is now safe:

function optChain(foo: Foo) {
    console.log(foo.bar?.baz.toUpperCase());
}

optChain({ bar: { baz: "hello" } }); // HELLO
optChain({}); // undefined

You should use optional chaining if you are not sure that your property accesses are safe and you want runtime checks to protect you.


On the other hand, non-null assertions have no effect whatsoever at runtime. It's a way for you to tell the compiler that even though it cannot verify that a property exists, you are asserting that it is safe to do it. This also has the effect of stopping the compiler from complaining, but you have now taken over the job of ensuring type safety. If, at runtime, the value you asserted as defined is actually undefined, then you have lied to the compiler and you might hit a runtime error:

function nonNullAssert(foo: Foo) {
    console.log(foo.bar!.baz.toUpperCase());
}

nonNullAssert({ bar: { baz: "hello" } }); // HELLO
nonNullAssert({}); //  TypeError: foo.bar is undefined

You should only use non-null assertions if you are sure that your property accesses are safe, and you want the convenience of skipping runtime checks.


Playground link to code

2 of 2
4

Those are completely different things.

The null assertion operator !. is you, the programmer, asserting to the compiler that you know for a fact that the property access cannot fail for reasons the compiler cannot prove. It is no more safe from a runtime error than any other assertion that you the programmer make to the compiler that you know better that it does.

const foo = null;
foo!.someProperty; // compiles but you will get a TypeError! Cannot read property 'someProperty' of null or undefined.

The other is the optional chaining operator. It is basically shorthand for this common Javascript pattern:

const something = foo && foo.bar && foo.bar.baz;

But it's better than just shorthand, because the above will fail if one of those values is falsey but some falsey values support property access. With the optional property accessor you just write:

const something = foo?.bar?.baz;

And you're done. And just like the Javascript version it's "safe" in that it's guaranteed not to result in a runtime error from trying to access a property of a null reference.

In the particular case you have there, you probably want something like this:

const enteredText = textInputRef.current?.value || '';

Where it's very clear that the result is a string no matter what.

🌐
GeeksforGeeks
geeksforgeeks.org › typescript › how-optional-chaining-works-in-typescript
How optional chaining works in TypeScript ? - GeeksforGeeks
March 22, 2022 - TypeScript Optional Chaining is the process of searching and calling variables, methods, parameters that might be nil in existence.
🌐
GitHub
github.com › tc39 › proposal-optional-chaining
GitHub - tc39/proposal-optional-chaining
es-optional-chaining (@claudepache) ecmascript-optionals-proposal (@davidyaha) Babylon implementation · estree: Null Propagation Operator · TypeScript: Suggestion: "safe navigation operator" Flow: Syntax for handling nullable variables · https://esdiscuss.org/topic/existential-operator-null-propagation-operator ·
Starred by 4.9K users
Forked by 72 users
Languages   HTML 97.2% | Shell 2.8%
🌐
Medium
medium.com › inside-rimeto › optional-chaining-in-typescript-622c3121f99b
Optional Chaining in TypeScript. Traversing tree-like structures safely… | by Neville Bowers | Inside Rimeto | Medium
December 4, 2019 - This statement is by far the most ... development-time tooling benefits. What’s the catch? TypeScript unfortunately does not yet support an optional chaining operator....
🌐
Klocwork
help.klocwork.com › 2024 › en-us › reference › js.ts.prefer.optional.chain.htm
JS.TS.PREFER.OPTIONAL.CHAIN
Because the optional chain operator only chains when the property value is null or undefined, it is much safer than relying upon logical AND operator chaining &&; which chains on any truthy value.
🌐
TypeScript ESlint
typescript-eslint.io › rules › prefer-optional-chain
prefer-optional-chain | typescript-eslint
?. optional chain expressions provide undefined if an object is null or undefined. Because the optional chain operator only chains when the property value is null or undefined, it is much safer than relying upon logical AND operator chaining ...
🌐
Reddit
reddit.com › r/typescript › how to enforce the use of optional chaining for any type object in typescript?
r/typescript on Reddit: How to enforce the use of optional chaining for any type object in TypeScript?
June 20, 2024 -

I'm trying to enforce the use of optional chaining for accessing properties of any type object in TypeScript to avoid potential runtime errors. For example, I want the following code to throw a TypeScript error:

    catch(e: any) {
        const code = e.code; // This should throw a TypeScript error
    }

But this code should not throw an error:

    catch(e: any) {
        const code = e?.code; // This should not throw a TypeScript error
    }

Is there a way to configure TypeScript to enforce this rule or any workaround to achieve this behavior?

🌐
Valentino G.
valentinog.com › blog › chaining
Using Optional Chaining in TypeScript and JavaScript
February 7, 2020 - It's a ternary operator stuffed with two void operators. The expression void 0 produces the undefined primitive. You can read the code like so: If _a is equal to undefined, then return undefined, otherwise return _a.code.
🌐
Dmitri Pavlutin
dmitripavlutin.com › javascript-optional-chaining
How to Use JavaScript Optional Chaining
Optional chaining, as a part of ES2020, changes the way properties are accessed from deep objects structures. Optional chaining is also available in TypeScript, starting from version 3.7.
🌐
Medium
sanjanahumanintech.medium.com › what-is-optional-chaining-in-typescript-7d6430e79917
What is Optional Chaining in TypeScript? | by Sanjana Human In Tech | Medium
October 30, 2023 - Optional Chaining is a feature in TypeScript that allows you to safely access deeply nested properties and methods of an object or array, without explicitly checking for the existence of each level. ... Optional Chaining Operator: ?.