Skip to content

Commit 21faf0f

Browse files
committed
Improve ZodFromValidatorBase handling of V["fields"] in ZodObject and ZodRecord with infer; fix branded types for VString; enforce "strip" on ZodObject; add tests for optional types
1 parent 9d98924 commit 21faf0f

File tree

2 files changed

+19
-16
lines changed

2 files changed

+19
-16
lines changed

packages/convex-helpers/server/zod.test.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -833,6 +833,9 @@ test("convexToZod complex types", () => {
833833

834834
const recordValidator = convexToZod(v.record(v.string(), v.number()));
835835
expect(recordValidator.constructor.name).toBe("ZodRecord");
836+
837+
const optionalValidator = convexToZod(v.optional(v.string()));
838+
expect(optionalValidator.constructor.name).toBe("ZodOptional");
836839
});
837840

838841
test("convexToZodFields", () => {

packages/convex-helpers/server/zod.ts

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1323,8 +1323,10 @@ export type ConvexToZod<V extends GenericValidator> = z.ZodType<Infer<V>>;
13231323
type ZodFromValidatorBase<V extends GenericValidator> =
13241324
V extends VId<GenericId<infer TableName extends string>>
13251325
? Zid<TableName>
1326-
: V extends VString<any, any>
1327-
? z.ZodString
1326+
: V extends VString<infer T, any>
1327+
? T extends string & { _: infer Brand extends string }
1328+
? z.ZodBranded<z.ZodString, Brand>
1329+
: z.ZodString
13281330
: V extends VFloat64<any, any>
13291331
? z.ZodNumber
13301332
: V extends VInt64<any, any>
@@ -1333,24 +1335,22 @@ type ZodFromValidatorBase<V extends GenericValidator> =
13331335
? z.ZodBoolean
13341336
: V extends VNull<any, any>
13351337
? z.ZodNull
1336-
: V extends VLiteral<any, any>
1337-
? z.ZodLiteral<V["value"]>
1338-
: V extends VObject<any, any, any, any>
1339-
? z.ZodObject<{
1340-
[K in keyof V["fields"]]: ZodValidatorFromConvex<
1341-
V["fields"][K]
1342-
>;
1343-
}>
1344-
: V extends VRecord<any, infer Key, any, any, any>
1338+
: V extends VLiteral<infer T, any>
1339+
? z.ZodLiteral<T>
1340+
: V extends VObject<any, infer Fields, any, any>
1341+
? z.ZodObject<
1342+
{
1343+
[K in keyof Fields]: ZodValidatorFromConvex<Fields[K]>;
1344+
},
1345+
"strip"
1346+
>
1347+
: V extends VRecord<any, infer Key, infer Value, any, any>
13451348
? Key extends VId<GenericId<infer TableName>>
13461349
? z.ZodRecord<
13471350
Zid<TableName>,
1348-
ZodValidatorFromConvex<V["value"]>
1349-
>
1350-
: z.ZodRecord<
1351-
z.ZodString,
1352-
ZodValidatorFromConvex<V["value"]>
1351+
ZodValidatorFromConvex<Value>
13531352
>
1353+
: z.ZodRecord<z.ZodString, ZodValidatorFromConvex<Value>>
13541354
: V extends VArray<any, any>
13551355
? z.ZodArray<ZodValidatorFromConvex<V["element"]>>
13561356
: V extends VUnion<any, any, any, any>

0 commit comments

Comments
 (0)