Exploring the world of TypeScript, I recently ventured into using zod for validating my fastify request/response. However, I hit a roadblock while trying to build schemas using the fastify-zod
plugin as it resulted in a compile error. This dilemma revolves around my user.schema.ts
import { z } from 'zod'
import { buildJsonSchemas } from 'fastify-zod';
export enum Role {
Agent = 'Agent',
Admin = 'Admin',
}
const createUserSchema = z.object({
email: z.string({
required_error: "Email is required",
invalid_type_error: "Email must be a string"
}).email(),
role: z.nativeEnum(Role, {
required_error: "Role is required"
}),
teamId: z.number({
required_error: "Team id is required"
})
});
export type CreateUserInput = z.infer<typeof createUserSchema>;
export const { schemas: userSchemas, $ref } = buildJsonSchemas({
createUserSchema //error here (compile)
});
The issue arises at the createUserSchema
with an accompanying error message:
(property) createUserSchema: z.ZodObject<{
email: z.ZodString;
role: z.ZodNativeEnum<typeof Role>;
teamId: z.ZodNumber;
}, "strip", z.ZodTypeAny, {
email: string;
role: Role;
teamId: number;
}, {
email: string;
role: Role;
teamId: number;
}>
Property 'brand' is missing in type 'ZodObject<{ email: ZodString; role: ZodNativeEnum<typeof Role>; teamId: ZodNumber; }, "strip", ZodTypeAny, { email: string; role: Role; teamId: number; }, { ...; }>' but required in type 'ZodType<unknown, ZodTypeDef, unknown>'.ts(2741)
types.d.ts(78, 5): 'brand' is declared here.
Models.d.ts(2, 59): The expected type comes from property 'createUserSchema' which is declared here on type 'Models<string>'
I am puzzled by this unfamiliar presence of:
Property 'brand' is missing in type
Do you have any insights into what might be causing this hiccup?
Edit:
These are the dependencies listed in my package.json file:
"dependencies": {
"@firebase/app-types": "^0.7.0",
"@prisma/client": "^4.3.1",
"dotenv": "^16.0.2",
"fastify": "^4.6.0",
"fastify-cors": "^6.1.0",
"fastify-zod": "^1.2.0",
"firebase": "^9.9.4",
"firebase-admin": "^11.0.1",
"zod": "3.18.0",
"typescript": "4.8.2"
},
After updating zod version to 3.18.0 from 3.17.2, I encountered this new obstacle:
Type instantiation is excessively deep and possibly infinite.ts(2589)