Jamal
Jamal4w ago

How can I infer typescript interfaces into a validator?

Example: I have a type called dog:
interface Dog {
name: string
}
interface Dog {
name: string
}
and I have a convex mutation:
const createDog = mutation({
args: {
dog: {
name: v.string()
}
},
handler(ctx, args) { ... }
})
const createDog = mutation({
args: {
dog: {
name: v.string()
}
},
handler(ctx, args) { ... }
})
in this example I have to manually type out the args using convex values even though I have a typescript interface. Can I create an inferred validator type based on my own interfaces to avoid code duplication? it would be useful to do something like:
const createDog = mutation({
args: {
dog: inferAsValidator<Dog>
},
handler(ctx, args) { ... }
})
const createDog = mutation({
args: {
dog: inferAsValidator<Dog>
},
handler(ctx, args) { ... }
})
5 Replies
Convex Bot
Convex Bot4w ago
Thanks for posting in <#1088161997662724167>. Reminder: If you have a Convex Pro account, use the Convex Dashboard to file support tickets. - Provide context: What are you trying to achieve, what is the end-user interaction, what are you seeing? (full error message, command output, etc.) - Use search.convex.dev to search Docs, Stack, and Discord all at once. - Additionally, you can post your questions in the Convex Community's <#1228095053885476985> channel to receive a response from AI. - Avoid tagging staff unless specifically instructed. Thank you!
Nerdkidchiki
Nerdkidchiki4w ago
Types and Validators in TypeScript: A Convex Cookbook
It can be tough to wrangle types to behave how you want them to. Thankfully, Convex was designed to make the experience with types perfect. Learn why ...
Nerdkidchiki
Nerdkidchiki4w ago
Zod with TypeScript for Server-side Validation and End-to-End Types
Use Zod with TypeScript for argument validation on your server functions allows you to both protect against invalid data, and define TypeScript types ...
erquhart
erquhart4w ago
You can't really create a validator based on a type because types don't execute at runtime. But you can do the inverse - create a Convex validator (you can optionally use Zod to get more comprehensive as the previous comment points out), and then infer your types from the validator:
const DogValidator = v.object({
name: v.string(),
})

type Dog = Infer<typeof DogValidator>
// { name: string }

const createDog = mutation({
args: {
dog: DogValidator,
},
handler() {...},
})
const DogValidator = v.object({
name: v.string(),
})

type Dog = Infer<typeof DogValidator>
// { name: string }

const createDog = mutation({
args: {
dog: DogValidator,
},
handler() {...},
})
Jamal
JamalOP4w ago
Okay thanks!

Did you find this page helpful?