One of the issues I've observed across various drafts is the confusing overlap between destructuring and pattern matching. A primary difference between destructuring and matching is that destructuring will match a missing value as undefined whereas pattern matching should fail.
Inspired by TypeScript's non-null assertion operator, I propose introducing a post-fix unary operator ! in matches that binds the preceding name only if the destructured value is truthy.
const val = {a: 1};
const {a, b} = val; // a => 1, b => undefined
const {a, b!} = value; // throws destructuring error
This would enable syntax for conditional if let expressions.
if (const {err!} = res) {
throw err;
}
This same syntax can be used with pattern matching:
const res = case (res) {
{err!} -> err,
{statusCode: 200} -> ok,
{statusCode!} -> mapStatusCode(statusCode),
}
I like the idea. Does the syntax work out, given all the ASI constraints, etc?
How would TypeScript itself adopt it? Doesn't it conflict with TypeScript's own use of !?
(This TypeScript conflict killed infix bang as sugar for the eventual-send proposal.)
To my knowledge, TypeScript never allows ! on the left side of a variable assignment, so this should never cause issues.
This would need to be its own proposal, at which point pattern matching could adopt it - while the potential difference between [[HasOwnProperty]] and undefined is something to consider, I don't think this proposal needs to be blocked on this syntax suggestion.
@ljharb , this could not be in its own proposal. The whole point is to unify syntax to ease learning and maximize likelihood of acceptance. Separating this proposal into a separate proposal would ensure that the pattern matching syntax would not have compatibility with destructuring syntax because of the undefined incompatibility.
I like the idea, but:
{err} -> err will always match if input is any non-null value, which make such syntax not very useful by default.! as TS non-null assertion is for both undefined and null, so for consistency, {err!} -> err should also fail if err is null.undefined, another main diff is [a, b] -> ... only match when the input have exactly two item.@chriskuech a syntax like that absolutely must be its own proposal, because it wouldn't just apply inside pattern matching - it'd have to work everywhere.
Conditional if let expressions are great for compact and readable code without the need to introduce variable in outer scope.
The proposal has been updated in #174. If you have any questions about the updated syntax, please file a new issue.