a quick code snippet
Validate and Infer Types With Zod
This is from Matt Pocock's appearance on the VSCode Youtube channel.
import { z } from 'zod'
const Data = z.object({
id: z.string()
name: z.string()
})
type DataType = z.infer(typeof Data)
fetch('/something')
.then((res) => res.json())
.then((result) => {
const data = Data.parse(result)
})
This will first validate the incoming data using Zod. A great first step if you're working with a third party API that you can't fully trust. After that, use the z.infer
to infer types from your validation object. You can now use DataType
as your types for that response.