colinhacks / zod

TypeScript-first schema validation with static type inference
https://zod.dev
MIT License
33.09k stars 1.15k forks source link

Add typed variant of parse, parseAsync, safeParse, and safeParseAsync #3629

Open wbobeirne opened 2 months ago

wbobeirne commented 2 months ago

Closes #1748. I didn't add any tests since this is build time and not run time, and it's just a wrapper around the existing methods, but if there are some tests you would find useful just let me know and I'll add 'em!

netlify[bot] commented 2 months ago

Deploy Preview for guileless-rolypoly-866f8a ready!

Built without sensitive environment variables

Name Link
Latest commit 6aefdeb1a184ff66c0042ead601ab143386f459b
Latest deploy log https://app.netlify.com/sites/guileless-rolypoly-866f8a/deploys/668cb09ef656a5000800353a
Deploy Preview https://deploy-preview-3629--guileless-rolypoly-866f8a.netlify.app
Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

mmkal commented 2 months ago

A thought - I know this is closer to what I originally proposed two years ago but what about making parse/safeParse/parseAsync generic, taking an options typearg object, instead? Would avoid expanding the API surface just for the sake of types:

-  parse(data: unknown, params?: Partial<ParseParams>): Output {
+  parse<Options extends {strict: boolean} = {strict: false}>(data: Options['strict'] extends true ? Input : unknown, params?: Partial<ParseParams>): Output {

Usage:

const S = z.string()

S.parse<{strict: true}>('x') // ok
S.parse<{strict: true}>(123) // ts error
S.parse(123) // no ts error
wbobeirne commented 2 months ago

I'm open to either approach, I'll defer to @colinhacks or any other maintainers if they have a preference.

If we go the <{strict:true}> route, it might be nice to provide a way to override the default with a declare module 'zod' so that you can be strict true by default, and require a <{ strict: false }> to allow incorrectly typed input to parse.