[Typescript] Zod in action

original code: Using type guards

type Ticket = {
  workshopId: string
  attendeeId: string
  discountCode?: string
}

// this is a type guard function
function isTicket(ticket: unknown): ticket is Ticket {
  return (
    Boolean(ticket) &&
    typeof ticket === 'object' &&
    typeof (ticket as Ticket).workshopId === 'string' &&
    typeof (ticket as Ticket).attendeeId === 'string' &&
    (typeof (ticket as Ticket).discountCode === 'string' ||
      (ticket as Ticket).discountCode === undefined)
  )
}

const ticket = JSON.parse(localStorage.get('ticket'))
//    ^?  any
if (isTicket(ticket)) {
  // now we know!
} else {
  // handle the case the data is not a ticket
}

 

Using Zod:

import { z } from "zod"

const Ticket = z.object({
  workshopId: z.string(),
  attendeeId: z.string(),
  discountCode: z.string().optional()
})
type Ticket = z.infer<typeof Ticket>

const rawTicket = JSON.parse(localStorage.get('ticket'))
const result = Ticket.safeParse(rawTicket);
if (result.success) {
  const ticket = result.data
  //    ^? Ticket
} else {
  // result.error will have a handy informative error
}

 

posted @ 2022-11-03 15:35  Zhentiw  阅读(22)  评论(0编辑  收藏  举报