[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 @   Zhentiw  阅读(22)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2021-11-03 [CSS] z-index
2021-11-03 [Javascript] Safely Access a Property on a JavaScript Array with Optional Chaining
2020-11-03 [Javascript] Broadcaster + Operator + Listener pattern -- 13. Repeat When Done with a Repeat Operator
2020-11-03 [Javascript] Broadcaster + Operator + Listener pattern -- 12. Repeat a broadcaster that is DONE
2017-11-03 [Angular] How to get Store state in ngrx Effect
2014-11-03 [Angular-Scaled web] 2. Architecture sub-modules
2014-11-03 [Angular-Scaled web] 1. Architecture and file structure
点击右上角即可分享
微信分享提示