Use “ZOD” to define the data type of response from AJAX in Typescript

Although you can use the interface to define your data schema from AJAX, but zod must be the better choice.

For Example:

Here is the sample code to get a response from the WordPress post endpoint.

import { z } from 'zod'

const Post = z.object({
  id: z.number(),
  date: z.string(),
  status: z.string(),
  title: z.object({
    rendered: z.string()
  }),
})

type PostType = z.infer<typeof Post>

const getPost = async () => {
  return await (await fetch(`https://www.yaoin.net/wp-json/wp/v2/posts/3615`)).json()
}

const doSomethingElse = (post: PostType) => {
  console.log('get post title', post.title.rendered)
}

(async () => {
  const post = Post.parse(await getPost())
  console.log(post.id)
  doSomethingElse(post)
})()