ts-pattern icon indicating copy to clipboard operation
ts-pattern copied to clipboard

How to match and use `P.select()` on recursive data structures?

Open jamesbrauman opened this issue 6 months ago • 0 comments

I'm enjoying the power and expressiveness of this library - thanks for creating and maintaining it! A problem I have run into is that it's not clear to me how to match against a recursive object - especially when I want to use P.select to select values.

Example:

type A = {
  kind: 'a',
  value: string
  child: A | B
}

type B = {
  kind: 'b',
  value: string
}

const a: A = {
  kind: 'a',
  value: 'hello',
  child: {
    kind: 'a',
    value: 'world',
    child: {
      kind: 'b',
      value: '!'
    }
  }
}

In this example, the object I want to match against (a) could have an arbitrary depth. I want to use P.select to select the value throughout the entire object regardless of it's shape.

(Note in this specific example I could just walk the tree but our project has multiple complex data structures we need to match against).

Is this possible with this library - if not, is there a recommended approach here? Thanks!

jamesbrauman avatar Jul 27 '25 23:07 jamesbrauman