tc39 / proposal-pattern-matching

Pattern matching syntax for ECMAScript
https://tc39.es/proposal-pattern-matching/
MIT License
5.45k stars 89 forks source link

Consider type annotations as pattern syntax #309

Open kaleidawave opened 9 months ago

kaleidawave commented 9 months ago

With type annotations potentially being added, I think it would be worth considering whether the patterns could be the same as type annotations. Type annotations would cover primitive literal types 1, "some string", true etc. and objects { tag: "a", data }, arrays etc. It would also allow referencing/reusability through the use of interfaces and type aliases.

This would allow this feature to be adopted quicker as existing type annotations could be used in patterns. It also reduces the work for type checkers to do narrowing in the matcher body.

Additional I think that the matching block should be the same AST as arrow function bodies. It should also copy the return syntax being the result of the body rather than introducing different semantics (or a forth return like keyword).

The result being something like

match (res) {
    when (number) => 5,
    when ({ tag: "number", data }) => data + 2,
    when (InterfaceX) => {
        for (const x of res.items) {
            if (x === res.expect) {
                return x;
            }
        }
        return null
    },
}
ljharb commented 9 months ago

That proposal is stage 1 with no clear path to ever reaching stage 2; if we block this proposal on that one we’ll never get pattern matching.

littledan commented 5 months ago

These two proposals are peers at Stage 1. Not sure how to make judgements like "no clear path to ever reaching stage 2" -- I am still hopeful.

That said, the core concept of type annotations is that types are treated as comments at runtime, so I don't think it's a good fit for pattern matching, which is supposed to do stuff.