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.

Answer from Donut on Stack Overflow
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";
๐ŸŒ
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:
Discussions

Does anyone miss operator overloading?
I like that in Haskell you can turn any regular function into an infix operator by surrounding it with backticks. So your example would be something like skullcup = cup `union` (skull `sub` convex_hull(cup `sub` handle `sub` lip)) Of course backticks are taken in JS but I'm sure we could find another chunk in the ASCII soup bowl to use! More on reddit.com
๐ŸŒ r/typescript
104
70
January 27, 2024
Nullish Coalescing Operator vs Logical OR
They are different, if you want value=0 to fall back to 1 you should use || otherwise use ?? More on reddit.com
๐ŸŒ r/typescript
4
2
July 13, 2022
Typescript & operator - Stack Overflow
I'm struggling to find the definition of the & operator in TypeScript. I have recently come across the following code: type IRecord = T & TypedMap ; What does that operato... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Spread operator
Afraid not. Javascript get syntax does not create a property that is enumerable. It can be accessed directly but won't be accessed via an object spread or a for/in loop. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get#using_getters_in_classes More on reddit.com
๐ŸŒ r/typescript
22
4
August 8, 2024
๐ŸŒ
Mimo
mimo.org โ€บ glossary โ€บ typescript โ€บ operator
TypeScript Operator: Syntax, Usage, and Examples
You use operators throughout your code to assign values, compare data, manipulate collections, or perform logic checks. TypeScript supports arithmetic, assignment, comparison, logical, bitwise, ternary, nullish coalescing, and spread operators.
๐ŸŒ
DEV Community
dev.to โ€บ tmaximini โ€บ typescript-bang-operator-considered-harmful-3hhi
Typescript: Bang operator considered harmful - DEV Community
December 3, 2020 - 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. Sounds difficult. But all it does is basically telling the compiler "this value can not be null or undefined". One of the great advantages of Typescript is that it checks your code instantly for any type errors (duh), so whenever you are working with an object or variable value that might be undefined, it gives you a warning.
Find elsewhere
๐ŸŒ
Graphite
graphite.com โ€บ guides โ€บ typescript-operators
Operators in TypeScript
This guide will cover the fundamental and advanced operators in TypeScript, providing a clear understanding of their syntax and practical usage. We'll explore various operators such as the ternary operator, spread operator, and more.
๐ŸŒ
TypeScript
typescriptlang.org โ€บ docs โ€บ handbook โ€บ 2 โ€บ everyday-types.html
TypeScript: Documentation - Everyday Types
JavaScript has three very commonly used primitives: string, number, and boolean. Each has a corresponding type in TypeScript. As you might expect, these are the same names youโ€™d see if you used the JavaScript typeof operator on a value of those types:
๐ŸŒ
Programiz
programiz.com โ€บ typescript โ€บ operators
TypeScript Operators
In TypeScript, an operator is a special symbol that checks, changes, or combines operands (values). In this tutorial, you will learn about TypeScript operators with the help of examples.
๐ŸŒ
Reflectoring
reflectoring.io โ€บ typescript-operators
Operators in TypeScript
August 1, 2023 - Bitwise operators in TypeScript operate on binary representations of numbers. They are useful for performing operations at the binary level, manipulating individual bits, working with flags, or optimizing certain algorithms that require low-level ...
๐ŸŒ
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.
๐ŸŒ
W3Schools
w3schools.com โ€บ js โ€บ js_operators.asp
W3Schools.com
When used on strings, the + operator is called the concatenation operator.
๐ŸŒ
TypeScript
typescriptlang.org โ€บ docs โ€บ handbook โ€บ 2 โ€บ keyof-types.html
TypeScript: Documentation - Keyof Type Operator
The keyof operator takes an object type and produces a string or numeric literal union of its keys.
๐ŸŒ
Reddit
reddit.com โ€บ r/typescript โ€บ does anyone miss operator overloading?
r/typescript on Reddit: Does anyone miss operator overloading?
January 27, 2024 -

Operator overloading is a programming language feature which allows you to define how operators such as + - * / work on particular types. It's usually considered an object orientated feature - when you define your class, you can define how instances behave when added with the '+' operator, etc. This allows math with types other than integer and floating point numbers to be written more naturally - vector and matrix arthmetic, or complex numbers, for example. It also allows languages which lack a native string type to implement string concatanation (for example the std::string in C++ implments a '+' operator for string concatanation).

The reason many languages, including TypeScript and JavaScript, purposely omit operator overloading is that it can make code harder to read - operators are easy to gloss over and may have unexpected effects. Most of the time it's better to be sure that 'math is math'.

I've been TypeScript full stack for the last three years, and gradually moving away from C++ before that, and have never really missed operator overloading.

However, I've been playing with 3D meshes in the last few weeks, defined in stl files, possibly with a view to designing something for printing in 3D. I want to combine an object which is functional - a cup - with one that is decorative - a skull, to create a skull cup that is both functional and decorative, and maybe something of a momento mori. (a skull is functional of course - keeps my brain safe in my head - but I don't see any functional value of printing one out in plastic). I have a formula for doing this while maintaining the functional aspects of the cup:

skullcup = skull - convex_hull(cup - handle - lip) + cup

The problem is the variables are 3D meshes not numbers and the operators are boolean union and difference functions that operate upon these meshes. I know how to write that in TypeScript, it's just horrible to read and emotionally speaking just isn't the same!

So it got me thinking - is there some npm package or way of subverting the language that will give me something more like operator overloading?

So that's my question. Does anyone miss operator overloading, and do you have a subitute for it, please?

To do this and keep the type-safety of TypeScript, one would perhaps have to define a language extension, like how tsx is an extension of TypeScript which allows React code to be nicely written nicely in a way that retains type checking, but that seems like overkill!


Now I've got a confession to make, I've been doing this in Python with a libary called PyMesh. I'm finding I love PyMesh except I can't quite get the last piece of the formula to work, which ever way I put it together it always seems to fall over at the final hurdle... but I hate Python!

Just to be clear, that's a matter of experience and person taste. Naturally here we think TypeScript is better and have our reasons, but anyone familiar with Python finding themselves stuck with TypeScript - the reverse of my present situation - totally has my sympathy!

So, just as an aside, if you know of any npm packages that can do unions, difference, and convex_hulls on meshes loaded from stl files, I'll bite your hand off for it! Please :-)

I'm aware ThreeJS can import from stl, but I don't think it can do these specific operations and save it back out. Or maybe I've just been using it wrong.

Python does have operator overloading, so that's a minor blessing, and probably what got me thinking about it. However, the formula shared above written out without operator overloading looks like this. I'm sharing this piece of syntax because it happens to be identical with TypeScript's syntax. Note I've rearranged a few commutative operations in a vain attempt to get my code to work:

skullcup = pymesh.boolean(
    cup,
    pymesh.boolean(
        skull,
        pymesh.convex_hull(
            pymesh.boolean(
                cup,
                pymesh.boolean(
                    handle,
                    lip,
                    'union',
                    'cork'),
                'difference',
                'cork')
        ),
        'difference',
        'cork'),
    'union',
    'cork')

So, I think you'll agree, in this particular case at least, the code is much nicer with operator overloading.

๐ŸŒ
TypeScript
typescriptlang.org โ€บ docs โ€บ handbook โ€บ advanced-types.html
TypeScript: Documentation - Advanced Types
Luckily, you donโ€™t need to abstract typeof x === "number" into its own function because TypeScript will recognize it as a type guard on its own. That means we could just write these checks inline. ... These typeof type guards are recognized in two different forms: typeof v === "typename" and typeof v !== "typename", where "typename" can be one of typeof operatorโ€™s return values ("undefined", "number", "string", "boolean", "bigint", "symbol", "object", or "function").
๐ŸŒ
Convex
convex.dev โ€บ typescript 101 โ€บ operators & control flow โ€บ ternary operator
Ternary Operator | TypeScript Guide by Convex
The ternary operator works best when you're picking between two values based on a simple condition. It keeps variable assignments clean and makes your intent obvious at a glance. That said, readability beats brevity every time. If you're nesting ternaries more than two levels deep or squinting to understand your own code, switch to if-else or extract the logic into a function. TypeScript's type inference works great with ternaries, but only when the code is clear enough to maintain.
๐ŸŒ
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 - The ! operator is a non-null assertion operator that tells the compiler that a variable or property is not null or undefined, and it should be treated as such. In this article, we will discuss how to use the !
๐ŸŒ
Reddit
reddit.com โ€บ r/typescript โ€บ nullish coalescing operator vs logical or
r/typescript on Reddit: Nullish Coalescing Operator vs Logical OR
July 13, 2022 -

Take this interface for example

interface Item {
  value?: number
}

Which among the two do you prefer if you will be accessing the value property of an item and why?

console.log(item.value ?? 1.00) // 1.00 is the fallback value
console.log(item.value || 1.00) // 1.00 is the fallback value

Personally, I prefer to use the nullish coalescing operator ?? for fallback values since it's more explicit and it sames me from the weird falsy values that JavaScript has.

๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ typescript โ€บ typescript_operators.htm
TypeScript - Operators
August 1, 2010 - TypeScript - null vs. undefined ... An operator defines some function that will be performed on the data. The data on which operators work are called operands.