DanielXMoore / Civet

A TypeScript superset that favors more types and less typing
https://civet.dev
MIT License
1.56k stars 33 forks source link

Optional-chained operators #1149

Open bbrk24 opened 8 months ago

bbrk24 commented 8 months ago

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 commented 8 months ago

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.

bbrk24 commented 8 months ago

A couple notes: