Skip to content

Commit

Permalink
feat(isMatching): Typecheck pattern when using isMatching wth 2 param…
Browse files Browse the repository at this point in the history
…eters
  • Loading branch information
gvergnaud committed Dec 14, 2024
1 parent b6d791a commit 16e2b2c
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 9 deletions.
8 changes: 4 additions & 4 deletions src/is-matching.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,10 @@ export function isMatching<const p extends Pattern<unknown>>(
* return input.name
* }
*/
export function isMatching<const p extends Pattern<unknown>>(
pattern: p,
value: unknown
): value is P.infer<p>;
export function isMatching<const T, const P extends P.Pattern<NoInfer<T>>>(
pattern: P,
value: T
): value is P.infer<P>;

export function isMatching<const p extends Pattern<any>>(
...args: [pattern: p, value?: any]
Expand Down
20 changes: 16 additions & 4 deletions tests/is-matching.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,11 +56,11 @@ describe('isMatching', () => {
}
});

it('type inference should be precise without `as const`', () => {
type Pizza = { type: 'pizza'; topping: string };
type Sandwich = { type: 'sandwich'; condiments: string[] };
type Food = Pizza | Sandwich;
type Pizza = { type: 'pizza'; topping: string };
type Sandwich = { type: 'sandwich'; condiments: string[] };
type Food = Pizza | Sandwich;

it('type inference should be precise without `as const`', () => {
const food = { type: 'pizza', topping: 'cheese' } as Food;

const isPizza = isMatching({ type: 'pizza' });
Expand All @@ -77,4 +77,16 @@ describe('isMatching', () => {
throw new Error('Expected food to match the pizza pattern!');
}
});

it('should reject invalid pattern when two parameters are passed', () => {
const food = { type: 'pizza', topping: 'cheese' } as Food;

isMatching(
{
// @ts-expect-error
type: 'oops',
},
food
);
});
});
3 changes: 2 additions & 1 deletion tests/matcher-protocol.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ describe('matcher protocol', () => {
match: (input) => {
return {
matched:
input instanceof Some && isMatching<any>(this.value, input.value),
input instanceof Some &&
isMatching<any, any>(this.value, input.value),
};
},
};
Expand Down

0 comments on commit 16e2b2c

Please sign in to comment.