Zod

What is Zod

Zod is a TypeScript-first schema declaration and validation library.

Zod is designed to be as developer-friendly as possible. The goal is to eliminate duplicative type declarations. With Zod, you declare a validator once and Zod will automatically infer the static TypeScript type. It’s easy to compose simpler types into complex data structures.

Why We Need Zod

image 19.png

interface Resp {
  id: number,
  name: string,
  isAdult: boolen
}
 
// truly response
const resp = {
  id: 10,
  neme: 'freddy',
  isAdult: 'ture'
}
 
/** 
  isAdult is not a boolean
  so, maybe the validator is like this
*/
 
const validate = (obj: any): boolean => {
  return obj !== null 
    && typeof obj === 'object'
    && typeof obj.id === 'number'
    && typeof obj.name === 'string'
    && typeof obj.isAdult === 'boolean'
}

cons

  • zero dependencies

  • works in nodeJS and most modern browsers

  • Tiny

  • It’s work on JS too, so not necessary to using typescript

  • Immutable: when use zod method on original zod schema, it will return a new instance

  • Concise

  • Functional approach

Ref