How to apply existing static type to schema? #3367
Replies: 2 comments 1 reply
-
I'd suggest to do the opposite — define the type from the schema: const schema = z.object({
name: z.string()
});
type FormData = z.infer<typeof schema>; If the schema has transformations, you can use |
Beta Was this translation helpful? Give feedback.
-
The previous response did not address the actual question. To provide more context: for technical reasons, I need to create an abstraction between two layers. The first layer must be entirely free of any libraries. Therefore, we need to define a contract at this layer. However, I would still like to use Zod in the other layer to validate against this contract. How can I make my Zod schema smart enough to throw me an error when it doesn't match the contract? // Layer A
interface ICreateGithubComment {
content: string;
}
// Layer B
const schema = z.object<ICreateGithubComment>({ content: z.string() }); |
Beta Was this translation helpful? Give feedback.
-
I have a statically defined type
FormData
and I would like to apply it to my schema so I cana) make sure that the schema matches the type
b) access the schema e.g. to check
schema.shape.name.isOptional()
I ended up extracting and typing the schema shape as following:
Is there a more idiomatic way to achieve this?
Beta Was this translation helpful? Give feedback.
All reactions