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

Nhan Nguyen
1 min readDec 17, 2023

--

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(),
})

➖ User type defined by Zod .infer():

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

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',
}

or:

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

or:

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

I hope you found it useful. Thanks for reading.

🙏 Let’s get connected! You can find me on:

--

--