Skip to content

parse.typed(...) or some kind of typed parse method #1748

Description

@mmkal

It'd be nice to have zod help the developer max out their chances of parsing a valid object, when it's manually constructed. Example:

const User = z.object({
  name: z.string().regex(/^\w+ \w+$/),
  age: z.number(),
})

User.parse({
  name: 'Bob',
  birthdate: new Date('1970-01-01'),
})

The above code compiles, but we have enough information to know that it'll throw a ZodError at runtime. It'd be nice if there was a method like

User.parse.typed({
  name: 'Bob',
  birthdate: new Date('1970-01-01'),
})

Where the expected input type was Input (from the ZodType<Output, Def, Input>) rather than unknown. So the above code would error because the developer used birthdate instead of age.

This would be especially useful for types with a custom .refine or .regex method or similar where it could be misleading to use just a type declaration:

const user: z.infer<typeof User> = {
  name: "Robert'; -- DROP TABLE Students; --"
  age: 40,
}

The above will compile, and implies that the const user is a validated User instance, but it isn't because name doesn't match the regex. The current options are to do the above, which is safe-looking at compile time, but unsafe at runtime, or to use .parse(...) which is unsafe at compile time and safe-ish at runtime (but will throw errors).

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions