Skip to content

Instantly share code, notes, and snippets.

@ehaynes99
Last active August 2, 2022 21:58
Show Gist options
  • Save ehaynes99/d0eda174fbe3761c94dcccddec23e452 to your computer and use it in GitHub Desktop.
Save ehaynes99/d0eda174fbe3761c94dcccddec23e452 to your computer and use it in GitHub Desktop.
Zod Models

Modeling with zod

Create a model

import { z } from 'zod'

export const Customer = z.object({
  firstName: z.string(),
  lastName: z.string(),
  age: z.number(),
  address: z.object({
    streetAddress: z.string(),
    city: z.string(),
    state: z.string(),
    postalCode: z.string(),
  }),
  contact: z.array(
    z.object({
      type: z.string(),
      value: z.string(),
    }),
  ),
})

// type and value have the same name
export type Customer = z.infer<typeof Customer>

Inferred type

Typescript can fully infer the type from the value: image

Usage

// either throws an error, or it's a valid Customer
const customer = Customer.parse(request.body)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment