Skip to content

Consider type annotations as pattern syntax #309

Open

Description

@kaleidawave

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
    },
}

Activity

  1. ljharb commented on Nov 24, 2023

    @ljharb
    Member

    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.

  2. littledan commented on Apr 11, 2024

    @littledan
    Member

    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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions