DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

Zod - TypeScript-first schema declaration and validation library #tips

Image description

Exporting a value and a type with the SAME NAME.

This is great when your app has runtime things that feel like types, like Zod schemas.

👉 Example:

We have:

➖ User value defined by Zod .object():

// Path: user.schema.ts
export const User = zod.object({
  id: zod.number(),
  name: zod.string(),
  email: zod.string().email(),
})
Enter fullscreen mode Exit fullscreen mode

➖ User type defined by Zod .infer():

// Path: user.schema.ts
export type User = zod.infer<typeof User>
Enter fullscreen mode Exit fullscreen mode

In another place, we can use both User value and User type:

// Path: sample.ts
const user: User = {
  id: 1,
  name: 'John Doe',
  email: 'john@sample.com',
}
Enter fullscreen mode Exit fullscreen mode

or:

// Path: sample.ts
const user = User.parse({
  id: 1,
  name: 'John Doe',
  email: 'john@sample.com',
})
Enter fullscreen mode Exit fullscreen mode

or:

// Path: sample.ts
const user: User = User.parse({
  id: 1,
  name: 'John Doe',
  email: 'john@sample.com',
})

Enter fullscreen mode Exit fullscreen mode

I hope you found it useful. Thanks for reading. 🙏
Let's get connected! You can find me on:

Top comments (0)