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
?
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
You can use
Zod
to create a schema for your interfacef
and then use the parse method to check if an object adheres to that schema.So in this example,
schema.parse(myObject)
will throw a ZodError ifmyObject
doesn’t match the structure defined by thef
interface. If the object is valid, it will be assigned tovalidatedObject
.According to the docs, you should follow two steps to do this.
schema.parse
method to do this.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: