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

Add type checking to isMatching pattern argument #188

Open
luisgrases opened this issue Aug 21, 2023 · 1 comment
Open

Add type checking to isMatching pattern argument #188

luisgrases opened this issue Aug 21, 2023 · 1 comment
Labels
enhancement New feature or request

Comments

@luisgrases
Copy link

luisgrases commented Aug 21, 2023

I would like to be able to type check the pattern that I am passing to isMatching. This would help me avoid mistakes when defining the pattern I want to check.

See the following example:

const foo = { bar: 42 }
isMatching({ hello: P.string }, foo)  // No ts-error

I would expect a type error here as hello: string is not part of the foo definition.

The following implementation would accomplish this but would lose the type guard:

export const isMatching = <T>(
  value: T,
  pattern: Pattern.Pattern<T>
): boolean => {
  return match(value)
    .with(pattern, () => true)
    .otherwise(() => false)
}
@luisgrases luisgrases added the enhancement New feature or request label Aug 21, 2023
@prepor
Copy link

prepor commented Feb 21, 2024

I don't understand why in the original implementation value is unknown. We can parameterize isMatching with value type and keep type guarding too. Here is my implementation:

export function canMatch<T, const P extends Pattern.Pattern<T>>(
  value: T,
  pattern: P
): value is P.infer<P> {
  return match(value)
    .with(pattern, () => true)
    .otherwise(() => false);
}

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

No branches or pull requests

2 participants