Capítulo 24 de 61

Chapter 24: Instanceof

Core Idea

z.instanceof(Class) validates that a value is an instance of a given class (built-in or user-defined), and z.property()/z.properties() let you further check specific properties on that instance.

Key Concepts

  • z.instanceof(Class): passes instanceof Class checks; works for user classes and built-ins alike (RegExp, URL, Error, etc.).
  • z.property(name, schema): used inside .check() to validate one property of the value (most useful paired with z.instanceof(), but works on any type).
  • z.properties({ ... }): declares several property checks at once from an object literal; spread the result into .check().

Code Examples

class Test { name: string; }
const TestSchema = z.instanceof(Test);
TestSchema.parse(new Test()); // ok
TestSchema.parse("whatever"); // throws

z.instanceof(URL);
z.instanceof(Error);

const httpsUrl = z.instanceof(URL).check(
  ...z.properties({
    protocol: z.literal("https:" as string),
    hostname: z.string().regex(z.regexes.domain),
  })
);
httpsUrl.parse(new URL("https://example.com")); // ok
httpsUrl.parse(new URL("http://localhost"));    // throws (wrong protocol)
  • What it demonstrates: validating both the class of an instance and specific properties on it in one schema.

Key Takeaways

  1. z.instanceof() is the way to validate third-party or built-in class instances that don't have a native Zod schema.
  2. z.property()/z.properties() let you assert on specific fields of an instance without converting it to a plain object first.
  3. These checks compose with .check() just like any other refinement-style check.

Connects To

  • Refinements: z.property() is implemented as a check, the same mechanism .refine() uses.
  • Custom: for validation logic that doesn't fit instanceof or property checks at all.