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

Pattern.nonNullable does not behave as expected #247

Closed
ItaiYosephi opened this issue Apr 15, 2024 · 2 comments
Closed

Pattern.nonNullable does not behave as expected #247

ItaiYosephi opened this issue Apr 15, 2024 · 2 comments

Comments

@ItaiYosephi
Copy link

ItaiYosephi commented Apr 15, 2024

Describe the bug
Pattern.nonNullable behave the same Pattern.not(Pattern.nullish)

Code Sandbox with a minimal reproduction case
https://codesandbox.io/p/sandbox/thirsty-frog-9965h3?file=%2Fsrc%2Findex.ts%3A20%2C14

provided this code

enum AnimalType {
  Dog = "dog",
  Cat = "cat",
}

interface Animal {
  type?: AnimalType;
  name: string;
}

const animal: Animal = { name: "Bobbie" };

match(animal)
  .with(
    // replace the next line with:
    // { type: Pattern.not(Pattern.nullish) },
    { type: Pattern.nonNullable },
    ({ name, type }) => `${name} the ${type}`
  )
  .with({ type: Pattern.optional(Pattern.nullish) }, ({ name }) => name)
  .exhaustive();

match(animal)
  .with(
    { type: Pattern.not(Pattern.nullish) },
    { type: Pattern.nonNullable },
    ({ name, type }) => `${name} the ${type}`
  )
  // without `Optional` - there's no TS error, but there is runtime error
  .with({ type: Pattern.nullish }, ({ name }) => name)
  .exhaustive();

I get this ts error
CleanShot 2024-04-16 at 11 21 30@2x

Versions

  • TypeScript version: 5.4.3
  • ts-pattern version: 5.1.1
  • environment: browser
@gvergnaud
Copy link
Owner

gvergnaud commented May 5, 2024

That's indeed a bug. I'll take a closer look when I get some time. In the meantime using P.not(P.nullish) instead of P.nonNullable is the alternative I'd recommend if you run into this issue

TS Playground for reference

@gvergnaud
Copy link
Owner

Fixed in 5.1.2!

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

2 participants