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
nullorundefined. 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 returnsnull.
- Kotlin refers to it as the safe call operator.
There are probably lots of other examples, too.
Answer from Donut on Stack OverflowYes. 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
nullorundefined. 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 returnsnull.
- Kotlin refers to it as the safe call operator.
There are probably lots of other examples, too.
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";
Does anyone miss operator overloading?
Nullish Coalescing Operator vs Logical OR
Typescript & operator - Stack Overflow
Spread operator
Videos
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.
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.
This looks like it's from the Intersection Types portion of the Language Specification. Specifically, the & is an intersection type literal. As for what it does:
Intersection types represent values that simultaneously have multiple types. A value of an intersection type A & B is a value that is both of type A and type B. Intersection types are written using intersection type literals (section 3.8.7).
The spec goes on to offer a helpful snippet to better understand the behavior:
interface A { a: number }
interface B { b: number }
var ab: A & B = { a: 1, b: 1 };
var a: A = ab; // A & B assignable to A
var b: B = ab; // A & B assignable to B
Because ab is both of type A and of type B, we can assign it to a and/or b. If ab were only of type B, we could only assign it to b.
The code you shared may be from this comment on GitHub, which mentions Intersection Types.
Worth noting that if you'd prefer to use interfaces over types (although they're largely similar) that you can typically use interface extension instead of type intersection like this:
// base type
interface Shape {
color: string;
}
// extension
interface Square extends Shape {
sideLength: number;
}
// intersection
type Square = Shape & {
sideLength: number;
}
See Also: Difference between extending and intersecting interfaces in TypeScript?