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

Improvements to P.infer and isMatching #302

Merged
merged 3 commits into from
Dec 15, 2024
Merged

Improvements to P.infer and isMatching #302

merged 3 commits into from
Dec 15, 2024

Conversation

gvergnaud
Copy link
Owner

@gvergnaud gvergnaud commented Dec 15, 2024

This release contains two changes:

Typecheck pattern when using isMatching with 2 parameter.

It used to be possible to pass a pattern than could never match to isMatching. The new version checks that the provide pattern does match the value in second parameter:

type Pizza = { type: 'pizza'; topping: string };
type Sandwich = { type: 'sandwich'; condiments: string[] };
type Food = Pizza | Sandwich;

const fn = (food: Pizza | Sandwich) => {
    if (isMatching({ type: 'oops' }, food)) {
        //                  👆 used to type-check, now doesn't!
    }
}

Do not use P.infer as an inference point

When using P.infer<Pattern> to type a function argument, like in the following example:

const getWithDefault = <T extends P.Pattern>(
  input: unknown,
  pattern: T,
  defaultValue: P.infer<T> //  👈
): P.infer<T> =>
  isMatching(pattern, input) ? input : defaultValue

TypeScript could get confused and find type errors in the wrong spot:

const res = getWithDefault(null, { x: P.string }, 'oops') 
//                                     👆           👆 type error should be here
//                                 but it's here 😬

This PR fixes this problem

@gvergnaud gvergnaud merged commit ba71cf1 into main Dec 15, 2024
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

Successfully merging this pull request may close these issues.

1 participant