ts-pattern icon indicating copy to clipboard operation
ts-pattern copied to clipboard

Add type checking to isMatching pattern argument

Open luisgrases opened this issue 2 years ago • 2 comments

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 avatar Aug 21 '23 23:08 luisgrases

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);
}

prepor avatar Feb 21 '24 13:02 prepor