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

Ability to select() tuple element as a whole #76

Closed
MikelArnaiz opened this issue Feb 16, 2022 · 1 comment
Closed

Ability to select() tuple element as a whole #76

MikelArnaiz opened this issue Feb 16, 2022 · 1 comment
Labels
enhancement New feature or request

Comments

@MikelArnaiz
Copy link

Consider an input made of tuples + enums

enum Foo { ... }
enum Bar { ... }
type State = 
  | [Foo.A, Bar.A, {age: number}]
  | [Foo.A, Bar.B, {name: string, age: number}]

Note I'm using the last tuple element for the data, when patter matching I use a wildcard on it. Then I destructure the handler selections to access data

.with([Foo.A, Bar.A, __], ([_foo, _bar, data]) => {
  // do something with data
})
.with([Foo.A, Bar.B, __], ([_foo, _bar, data]) => {
  // do something with data
})

The only workaround with select I know is to list all data's properties

.with([Foo.A, Bar.A, { age: select('age')}], (data) => {
  // ...
})
.with([Foo.A, Bar.B, { name: select('name'), age: select('age') }], (data) => {
  // ...
})

Describe the solution you'd like

It would be great to select the wildcarted element

.with([Foo.A, Bar.A, __.select], (data) => {
  // ...
})
.with([Foo.A, Bar.B, __.select], (data) => {
  // ...
})

Describe alternatives you've considered
A workaround I'm using is to move the selection outside the pattern matching, but this doesn't act as a wildcard and only works if multiple cases have same data

const selectData = {
  name: select('name'),
  age: select('age')
}

...

.with([Foo.A, Bar.A, selectData], (data) => {
  // ...
})
.with([Foo.A, Bar.B, selectData], (data) => {
  // ...
})
@MikelArnaiz MikelArnaiz added the enhancement New feature or request label Feb 16, 2022
@gvergnaud
Copy link
Owner

gvergnaud commented Feb 17, 2022

Hey, I believe you can already do this with the current version, only it's select() instead of __.select. Here is a sandbox demonstrating this:

https://codesandbox.io/s/broken-frog-wmx243?file=/src/index.ts

import { match, select } from "ts-pattern";
  
const f = (state: State) =>
  match(state)
    // data: { age: number }
    .with(["Foo.A", "Bar.A", select()], (data) => data)
    // data: { name: string, age: number }
    .with(["Foo.A", "Bar.B", select()], (data) => data)
    .exhaustive();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants