Search code examples
javascripttypescriptzod

Type checks in Typescript with Zod


I have the code:

import { z } from "zod";

interface f {
   tmp: number;
}

How can I now check that object like { tmp: 123 } has same structure as f?


Solution

  • You can use Zod to create a schema for your interface f and then use the parse method to check if an object adheres to that schema.

    import { z, ZodError } from "zod";
    
    interface f {
     tmp: number;
    }
    
    const schema = z.object({
     tmp: z.number()
    });
    
    const myObject = { tmp: 123 };
    
    try {
     const validatedObject: f = schema.parse(myObject);
     console.log("Object is valid:", validatedObject);
    } catch (error) {
     if (error instanceof ZodError) {
      console.error("Object is not valid:", error.errors);
     } else {
      throw error;
     }
    }
    

    So in this example, schema.parse(myObject) will throw a ZodError if myObject doesn't match the structure defined by the f interface. If the object is valid, it will be assigned to validatedObject.


    Update:

    The z.object method allows you to dynamically create a schema based on the structure of the f interface.

    import { z, ZodError } from "zod";
    interface f {
      tmp: number;
    }
    const schema = z.object(
      Object.fromEntries(
        Object.entries<Record<string, z.ZodType<any, any, any>>>({
          tmp: z.number(),
        })
      )
    );
    
    const myObject = { tmp: 123 };
    
    try {
      const validatedObject: f = schema.parse(myObject);
      console.log("Object is valid:", validatedObject);
    } catch (error) {
      if (error instanceof ZodError) {
        console.error("Object is not valid:", error.errors);
      } else {
        throw error;
      }
    }
    

    This way you don't have to manually list all the fields in z.object. This code dynamically creates a schema based on the fields defined in the f interface.