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

Discriminated unions? #12

Open
ivnsch opened this issue Nov 30, 2022 · 2 comments
Open

Discriminated unions? #12

ivnsch opened this issue Nov 30, 2022 · 2 comments

Comments

@ivnsch
Copy link

ivnsch commented Nov 30, 2022

I was trying to switch ("match style") over enum cases with fields, but this seems not to be possible. Example (src):

type AppEvent =
  | { kind: "click"; x: number; y: number }
  | { kind: "keypress"; key: string; code: number }
  | { kind: "focus"; element: HTMLElement };

function handleEvent(event: AppEvent) {
  switch (event.kind) {
    case "click":
      // We know it is a mouse click, so we can access `x` and `y` now
      console.log(`Mouse clicked at (${event.x}, ${event.y})`);
      break;
    case "keypress":
      // We know it is a key press, so we can access `key` and `code` now
      console.log(`Key pressed: (key=${event.key}, code=${event.code})`);
      break;
    case "focus":
      // We know it is a focus event, so we can access `element`
      console.log(`Focused element: ${event.element.tagName}`);
      break;
  }
}

Potential feature request, or maybe it's already possible and I'm missing something?

@jkomyno
Copy link

jkomyno commented Dec 1, 2022

Hi @ivanschuetz, it seems you're referring to a TypeScript limitation (which I believe is solved in TypeScript v4.9, btw).
For type-safe pattern matching in TypeScript, I strongly recommend the excellent ts-pattern library.

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

No branches or pull requests

3 participants