skip to Main Content

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?

2

Answers


  1. 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.

    Login or Signup to reply.
  2. According to the docs, you should follow two steps to do this.

    1. Define the Zod object schema: You can simply create a schema that matches your object.
    const fSchema = z.object({
        tmp: z.number(),
    });
    
    1. Validate the object: You can use schema.parse method to do this.
    fSchema.parse(obj);
    

    If the schema does not match, it will throw an error. You need to use the try#catch chain to prevent your app breaks.

    So the final code will be like this:

    import { z } from 'zod';
    
    interface f {
        tmp: number;
    }
    
    // Create a Zod schema that matches the structure of interface `f`
    const fSchema = z.object({
        tmp: z.number(),
    });
    
    // Example object to validate
    const obj = { tmp: 123 };
    
    // Validate the object against the schema
    try {
        fSchema.parse(obj);  // If the object matches the schema, this will pass
        console.log('Object is valid');
    } catch (error) {
        console.error('Object is invalid', error);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search