Skip to content

Commit 510b927

Browse files
committed
Add type narrowing to Vitest schemaMatching test
Demonstrates using assert with .is() for type narrowing after schemaMatching validation, since schemaMatching alone doesn't narrow types in TypeScript.
1 parent dc8633d commit 510b927

1 file changed

Lines changed: 20 additions & 6 deletions

File tree

packages/common/test/Type.test.ts

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3065,14 +3065,28 @@ describe("Standard Schema V1", () => {
30653065
});
30663066

30673067
test("Vitest schemaMatching interoperability", () => {
3068-
expect(1).toEqual(expect.schemaMatching(PositiveInt));
3068+
const value: unknown = 42;
3069+
expect(value).toEqual(expect.schemaMatching(PositiveInt));
30693070

3070-
const user = {
3071-
name: "Alice",
3072-
age: 30,
3073-
};
3071+
// Note: schemaMatching validates but doesn't narrow types;
3072+
// use assert with .is() for narrowing
3073+
assert(PositiveInt.is(value));
3074+
// The type is narrowed.
3075+
expectTypeOf(value).toEqualTypeOf<PositiveInt>();
3076+
3077+
const User = object({
3078+
name: NonEmptyTrimmedString100,
3079+
age: PositiveInt,
3080+
});
3081+
type User = typeof User.Type;
3082+
3083+
const data: unknown = { name: "Alice", age: 30 };
3084+
expect(data).toEqual(expect.schemaMatching(User));
3085+
assert(User.is(data));
30743086

3075-
expect(user).toEqual({
3087+
// https://vitest.dev/blog/vitest-4.html#expect-schemamatching
3088+
// Why their example tests props separately?
3089+
expect(data).toEqual({
30763090
name: expect.schemaMatching(NonEmptyTrimmedString100),
30773091
age: expect.schemaMatching(PositiveInt),
30783092
});

0 commit comments

Comments
 (0)