Add type checking to isMatching pattern argument
luisgrases opened this issue · comments
Luis Grases commented
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)
}
Andrew Rudenko commented
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);
}