Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optional-chained operators #1149

Open
bbrk24 opened this issue Apr 4, 2024 · 2 comments
Open

Optional-chained operators #1149

bbrk24 opened this issue Apr 4, 2024 · 2 comments
Labels
proposal Proposal or discussion about a significant language feature

Comments

@bbrk24
Copy link
Contributor

bbrk24 commented Apr 4, 2024

Related: #897

Here's a situation I've run into before: given an optional array, return one more than its length if it's defined, and some fallback value (e.g. 0) if it isn't. Currently this can be done in two ways:

lenPlusOne := (arr?: number[]) => if arr? then arr.# + 1 else 0
lenPlusOne := (arr?: number[]) => (arr?.# ?? -1) + 1

The first one is a little verbose, especially if it's embedded in a longer expression. The second one is less obvious why it works, and doesn't easily accommodate a configurable fallback value.

C#'s mathematical operators are optional-chained by default, so this can be written as

int LengthPlusOne(List<int>? l) => l?.Count + 1 ?? 0;

While we can't change the behavior of the existing JS operators -- after all, null + '' is still meaningful -- it would be nice for there to be a syntax for this, e.g. ?+.

@edemaine
Copy link
Collaborator

edemaine commented Apr 4, 2024

So if I understand correctly, the proposal is arr?.# ?+ 1 ?? 0. Looks nice to me! I imagine it could work for custom operators, instanceof, in, etc.

@edemaine edemaine added the proposal Proposal or discussion about a significant language feature label Apr 4, 2024
@bbrk24
Copy link
Contributor Author

bbrk24 commented Apr 4, 2024

A couple notes:

  • If the pipe counts as an operator (which it might not — see Cannot create operator with same precedence as pipe #1050), this supersedes Non-null pipe ?|> #897.
  • If assignment operators are included in this, the behavior it would imply for ?= is the exact opposite of its current behavior.
  • Less of an observation and more of a question: does it make sense to extend this to unary operators? x?++ is reminiscent of optional index access / calls, but ?-x looks a little strange.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
proposal Proposal or discussion about a significant language feature
Projects
None yet
Development

No branches or pull requests

2 participants