Let’s validate your typescript interfaces using Zod

Krina Wibisana
bhinneka-tech
Published in
3 min readNov 7, 2022
https://static.tvtropes.org/pmwiki/pub/images/zod_3.jpg

What is Zod?

Zod is a TypeScript-first schema declaration and validation library. I’m using the term “schema” to refer to any data type, from a simple broadly string to a complex nested object.

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 more straightforward types into complex data structures.

https://github.com/colinhacks/zod

Usually, we write an interface like this

interface IDate {
id: string;
date: number;
month: string;
year: number;
}

But this interface will not guarantee that the date field is a number, and if it has a different type when we use data from API, the response gives the date field is a string, typescript has many limitations, and typescript is not only giving the type system at runtime.

So what is the solution? There are so many typescript interfaces validator, like validator-fluent, ts-interface-checker, Typebox, io-ts, or Zod. All of these validators will help you to validate all of your objects that represent your typescript interfaces, and validate the type system at runtime.

But I choose Zod to validate my objects, because many tutorials out there, completed documentation, and a lot of developers use Zod. First of all, if you want to use Zod, install Zod first in your project.

npm i zodoryarn add zod

Below is an example of how Zod creates an object:

import { z } from 'zod';export const Date = z.object({
id: z.string(),
date: z.number(),
month: z.string(),
year: z.number(),
});

As you can see, the first thing that we write is an import z from zod. This object will validate your data at runtime, then we can create a relative definition to simpler the type.

export type ZDate = z.infer<typeof Date>;

Then we will use this type to validate our data from API. Below is the response:

{
id: '0001',
date: 7,
month: 'November',
year: 2022,
}

Now we will create a variable to save this response from API:

const fetchDate = async () => {
try {
const date = await fetch('/date');
return date;
catch (err) {
throw err;
}
}

The code above seems there is no problem, but if you hover your mouse over the variable date it will show you a non-sense type of date.

const date: {
id: string,
date: number,
month: string,
year: number,
}
____________________________________________________________________
const date = await fetch('/date');

Confuse? Yes, of course, sometimes I always get rid of this 😔. Zod help you to remove this error. Just add ZDate to variable date.

const fetchDate = async () => {
try {
const date: ZDate = await fetch('/date');
return date;
catch (err) {
throw err;
}
}

It will give you no error because have the same type. Zod also can help input/output for the fetch function, it will validate if the response is an error.

type ZResponse<Input, Output> = {
data: Output;
} | {
error: ZodError<Input>
}

The code above explained that if the fetch function is successful, it will return the data, in another way if the fetch function response is failed, it will give an error.

Zod is not a villain for us, only for Superman. Zod will help us to create scheme validation of our typescript interfaces.

“Welcome to a world of pain.” (Zod, Injustice: Gods Among Us)

--

--