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

Handling of undefined typings in tuples #213

Open
kevinresol opened this issue Jan 11, 2024 · 1 comment
Open

Handling of undefined typings in tuples #213

kevinresol opened this issue Jan 11, 2024 · 1 comment

Comments

@kevinresol
Copy link

kevinresol commented Jan 11, 2024

Describe the bug
In the code below, all occurrences of v1 and v2 are inferred as string | undefined but in fact they should be string because the undefined cases are already handled.

const getOptionalString: () => string | undefined = () => Math.random() > 5 ? undefined : 'foo';

const value = match([getOptionalString(), getOptionalString()])
  .with([undefined, undefined], () => 0)
  .with([P.select(), undefined], (v1) => 1) // BAD: v1 is inferred as string|undefined but should be just string
  .with([undefined, P.select()], (v2) => 2)
  .otherwise(([v1, v2]) => 3);

In fact, it works if the pattern is a single value instead of a tuple:

const value = match(getOptionalString())
  .with(undefined, () => 0)
  .otherwise((v) => 1); // GOOD: v is inferred as string without undefined

Code Sandbox with a minimal reproduction case
https://codesandbox.io/p/sandbox/crazy-galileo-3zsfmh

Versions

  • TypeScript version: 5.1.6
  • ts-pattern version: 5.0.6
  • environment: N/A (it happens at dev time)
@kevinresol kevinresol changed the title Handling of undefined in tuples Handling of undefined typings in tuples Jan 11, 2024
@gvergnaud
Copy link
Owner

This behavior is expected. In order to support this we would need to distribute unions in the input type even without using .exhaustive() and this is pretty expensive in terms of type checking time.

See the discussion in issue #145 for some additional context on how type narrowing and exhaustive work in ts-pattern

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