Use ts type in Zod
i have a type that i am importing from a 3rd party package. is there a way i can use this type and put it my object schema. if i just make it an enum and i update the 3rd party package and they change these types, my code would be wrong
2 Replies
@Joey9 do like this
const emailTypes = ['func1', 'func2', 'func3'] as const;
const mySchema = z.object({
type: z.enum(emailTypes),
});
you can also use a type level assertion to make sure your emailTypes array does not go out sync with the 3rd party package
https://www.typescriptlang.org/play/?#code/PTAEEsFsAcHsCcAuBTAJqRBPayBcoAoLHUAUUgENwAbAeUWgBVtlQBeUAcgGdwBzAHYBXaJ1AAfLuAEA3cCjGTOlPuADG1aQGtFXeMjWwZyeJl2dklGgH01ACwoC+yc5arVOAbgIFDA7oigbjTMONzsoADaPPzCogA0UrLyLonKFKoa2pwAuqAU4X4B3kQsoACC3NwmiKQAjkIU1AA8jIkAqgB8EZGMecgAHigCqOGR7XkA-FETQUPII2N9oNOI8EKs+ALIxvCgWzsm3kWBlFrIAMpC+qHI3ACyFIj2+GsbEW+s3E-g3ABm4DuFSqNXqjRa5Hc9CYLESxGQsD+QSs1Fu3EiwkgACMTDlOt4gA
TS Playground - An online editor for exploring TypeScript and JavaS...
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
