I think the answer is that humans are still smarter than typecheckers. I know that's not satisfying, but it's true. The typechecker typically uses just conditional statements to determine whether something can be null. But this code example feels a little contrived. I would probably restructure the code like this:

var myArray: (Array<any> | null);
if (cnd) {
  elt.key = value;
  myArray = [elt];
} else {
  myArray = null;
}

This removes those two oddities.

Answer from jack on Stack Overflow
🌐
Bobby Hadz
bobbyhadz.com › blog › typescript-question-mark-dot
What is the ?. operator (optional chaining) in TypeScript | bobbyhadz
If the property is populated on the object, the optional chaining operator (?.) returns the specified value in the array.
🌐
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.
🌐
Educative
educative.io › answers › how-to-use-a-question-mark-in-typescript-variables
How to use a question mark in TypeScript variables
The question mark in typescript can be used to mention that a variable is optional or to pre-check if a member variable is present for an object.
🌐
Graphite
graphite.com › guides › typescript-operators
Operators in TypeScript
The spread operator (...) allows an iterable such as an array or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected. ... The in operator returns true if the specified property is contained in the specified object or its prototype chain. ... In TypeScript, the question mark is used in two contexts.
🌐
Omarileon
omarileon.me › blog › typescript-double-question-mark
mari. | Demystifying TypeScript's Double Question Mark: Nullish Coalescing
January 25, 2024 - As well as the null coalescing operator, you might also find the less commonly used Nullish coalescing assignment operator used in TypeScript - double question marks followed by equals.
🌐
Gyata
gyata.ai › typescript › typescript-question-mark-operator
TypeScript Question Mark Operator | Gyata - Learn about AI, Education & Technology
The TypeScript Question Mark Operator is a powerful tool that can simplify and improve your code. It provides a safe way to access nested object properties, call functions, and access array indices. However, it should be used wisely and sparingly, keeping in mind its short-circuiting behavior ...
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Operators › Optional_chaining
Optional chaining (?.) - JavaScript | MDN
You can also use the optional chaining operator with bracket notation, which allows passing an expression as the property name: ... This is particularly useful for arrays, since array indices must be accessed with square brackets.
Find elsewhere
🌐
Delft Stack
delftstack.com › home › howto › typescript › question mark in typescript
Question Mark Operator in TypeScript | Delft Stack
January 30, 2023 - The question mark or ? has relieved the users by defining optional parameters. Moreover, the ? operator can also act as a shorthand for checking if a certain attribute of an object is null or undefined.
🌐
Medium
medium.com › totally-typescript › what-does-the-question-mark-dot-mean-in-javascript-or-typescript-9d7d744f6077
What Does the ?. Question Mark Dot Mean in JavaScript or TypeScript? | by Dr. Derek Austin 🥳 | Totally TypeScript | Medium
May 16, 2023 - What Does the ?. Question Mark Dot Mean in JavaScript or TypeScript? Unraveling the mystery of the ?. optional chaining operator with practical examples Introduction: Optional Chaining in JS / TS …
🌐
freeCodeCamp
freecodecamp.org › news › how-the-question-mark-works-in-javascript
How the Question Mark (?) Operator Works in JavaScript
February 3, 2021 - By Nishant Kumar The conditional or question mark operator, represented by a ?, is one of the most powerful features in JavaScript. The ? operator is used in conditional statements, and when paired with a :, can function as a compact alternative ...
🌐
EDUCBA
educba.com › home › software development › software development tutorials › typescript tutorial › typescript question mark
TypeScript Question Mark | Complete Guide to TypeScript Question Mark
April 11, 2023 - As it is supported with TypeScript 3.7 version, called Optional chaining. This variant, the existential operator ‘?.’ is used to soak up all the null references. With this, we shall conclude the topic ‘TypeScript question mark’. We have seen what TypeScript question mark is and its syntax.
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
GeeksforGeeks
geeksforgeeks.org › why-use-question-mark-in-typescript-variable
Why use Question Mark in TypeScript Variable? - GeeksforGeeks
October 14, 2024 - The question mark in TypeScript is used to mark a variable as optional, allowing it to be omitted or set to undefined. This is commonly used in object properties and function parameters, enhancing flexibility by making variables non-mandatory.
🌐
DEV Community
dev.to › danywalls › simplify-your-typescript-code-with-optional-chaining-and-nullish-coalescing-37on
Simplify Your Typescript Code with Optional Chaining and Nullish Coalescing - DEV Community
May 23, 2023 - The double question mark (??) checks if the left-hand side value is nullish (null or undefined) and provides the right-hand side value as the default if needed. Nullish coalescing ensures that we always have a valid jersey number, even if it's ...
🌐
Becomebetterprogrammer
becomebetterprogrammer.com › typescript-question-mark
Understanding the Question Mark (?:) in TypeScript - Become A Better Programmer
April 25, 2022 - In the initial example, we noticed the usage of the question mark with a colon (?:) when defining the properties of an interface. In a similar way, we can do so this when defining a class. class Car { id: string; brand: string; model: string; year: number; price?: number; } This gives the flexibility to not having the need to provide values to all properties of a class. We can also define optional parameters when creating functions in TypeScript.
🌐
egghead.io
egghead.io › lessons › typescript-use-the-optional-chaining-operator-in-typescript
Use the Optional Chaining Operator in TypeScript | egghead.io
[5:29] If you were to work with arrays, you can use the syntax to access array indices, for example. Finally, there's a third version of the optional chaining syntax. That's used for working with functions. To demonstrate the syntax, let me refactor our property to a method. Let's make sure this method is optional. [5:55] We can now call this function in our optional property chain by stating the name and then the syntax question mark dot, and parentheses for calling the function.
Published   February 17, 2021
Top answer
1 of 15
432

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";
🌐
Webdevtutor
webdevtutor.net › blog › typescript-syntax-double-question-mark
Mastering TypeScript Syntax: The Double Question Mark Trick
It checks if the left-hand operand is null or undefined before accessing its property or method. If it is null or undefined, it returns undefined instead of throwing an error. ... const person = { name: 'John', age: 30 }; console.log(person?.address?.street); // prints "undefined" In this example, ...