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

Wildcard and select() not working on property matching #40

Closed
moifort opened this issue Jul 20, 2021 · 3 comments
Closed

Wildcard and select() not working on property matching #40

moifort opened this issue Jul 20, 2021 · 3 comments
Labels

Comments

@moifort
Copy link

moifort commented Jul 20, 2021

Describe the bug
Wildcard __ and select() not working on property matching. As a workaround I use __.number

Code Sandbox with a minimal reproduction case
Result on console

https://codesandbox.io/s/nervous-turing-8cffw?file=/src/index.ts:0-937

Versions

  • TypeScript version: 4.2.3
  • ts-pattern version: 3.2.1
  • environment: node 14

Sample code

import { match, select, __ } from "ts-pattern";

type Id = { teamId: number } | { storeId: number };

const selectedId: Id = { teamId: 1 };

// Bug with wildcard
const bugWildcard = match<Id>(selectedId)
  .with({ storeId: __ }, () => "storeId")
  .with({ teamId: __ }, () => "teamId")
  .exhaustive(); // Return storeId instead of teamId

console.log(
  "WILDCARD BUG",
  "match result:",
  bugWildcard,
  "value to match:",
  selectedId
);

// Bug with select
const value = match<Id>(selectedId)
  .with({ storeId: select() }, (storeId) => storeId)
  .with({ teamId: select() }, (teamId) => teamId)
  .exhaustive(); // Return nothing

console.log(
  "SELECT BUG",
  "match result:",
  value,
  "value to match:",
  selectedId
);

// Working with __.number
const number = match<Id>(selectedId)
  .with({ storeId: __.number }, () => "storeId")
  .with({ teamId: __.number }, () => "teamId")
  .exhaustive();

console.log("WORKING", "match result:", number, "value to match:", selectedId);
@gvergnaud
Copy link
Owner

gvergnaud commented Jul 21, 2021

I think what's happening is that since __ and select() always match, if you try to match on a property that doesn't exist on an object, it's actually undefined which matches the pattern.

It would probably make more sense if { abc: __ } was matching only if the abc key exists on the input, though. Is this what you were expecting?

I'll have a look at the TC39 pattern matching proposal to check how they plan to handle this case

@moifort
Copy link
Author

moifort commented Jul 21, 2021

@gvergnaud thanks for your quick answer!

@gvergnaud
Copy link
Owner

Fixed in v3.2.2!

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

No branches or pull requests

2 participants