Third-party class instances
Validate values returned by third-party libraries while retaining their class behavior.
Zod · Module
z.instanceof(Class) validates that an input is an instance of a specified class. Successful parsing preserves the original object, including its prototype and identity.
Use z.instanceof(Class) when input must be an instance of a particular class. Parsing preserves the original instance rather than cloning it, so its prototype, methods, extra properties, and object identity remain intact.
z.instanceof(Class)| Name | Type | Description |
|---|---|---|
Class | class constructor | The class constructor whose instances should be accepted. |
A Zod schema that validates whether input is an instance of the supplied class and returns the original instance on success.
.properties() when selected instance properties also need validation..properties() retains the instance check while narrowing the inferred type based on the supplied property schemas.z.instanceof() for class instances, not as a general replacement for template-literal validation.import { z } from "zod";
class User {
constructor(public name: string) {}
}
const UserSchema = z.instanceof(User);
const user = UserSchema.parse(new User("Ada"));
console.log(user.name); // Ada
// UserSchema.parse({ name: "Ada" }); // throwsThe schema accepts a User instance and returns that same object; a structurally similar plain object fails.
Validate values returned by third-party libraries while retaining their class behavior.
Accept only built-in objects such as URLs, regular expressions, or errors.
Check selected fields on a class instance without converting it into a plain object.
z.instanceof() validate?z.instanceof(User) checks whether the input is an instance of User. A User instance parses successfully, while a non-instance such as a string fails.
Follow-up: How can you validate fields on the instance too? Use the instance schema's .properties() method to apply property schemas while preserving the instance.
The parsed result is the exact object supplied to the schema. This differs from z.object(), which does not preserve the instance in the same way.
Follow-up: How would you verify identity? Store the instance, parse it, and compare the result with ===; the comparison should be true.
z.instanceof() especially useful?It is useful for classes from third-party libraries, such as RegExp, URL, and Error. The class constructor is passed directly to z.instanceof().
Follow-up: Which Zod construct should be preferred for template literal types? Use z.templateLiteral() rather than z.instanceof().
z.object()z.instanceof().properties()z.property()z.templateLiteral()z.check()