I'm sure this has been raised before, but I couldn't find a satisfying answer. Since the input argument of parse(input: unknown), is of type unknown, the parse method can accept anything and guarantee the type of the output. However, in many cases, this seems to sidestep the whole point of typescript, turning what would be compile-time errors into runtime errors. Consider this example:
import { z } from 'zod'
const ExampleSchema = z.object({
name: z.string(),
})
type Example = z.infer<typeof ExampleSchema>
export function exampleRaw(): Example {
return {
// typescript compile-time error
wrongKey: 'Foo',
}
}
export function exampleParse(): Example {
// no compile-time error
return ExampleSchema.parse({
wrongKey: 'Foo',
})
}
In this case above, we'd be better of without zod at all, since adding the parse method obfuscates the compile-time error. In this simple example, raw typescript is preferable, but one might imagine wanting to use some features of zod, like transform or the fact that passthrough is false by default to have more precise control over which properties come out of the function.
We can build a function like this: which I think would do everything we want, getting us both the power of zod and the power of standard compile-time type checking.
export function typedParse<T extends z.input<typeof ExampleSchema>>(input: T): Example {
return ExampleSchema.parse(input)
}
export function exampleTypedParse(): Example {
// typescript compile-time error
return typedParse({
wrongKey: 'Foo',
})
}
The question is, why isn't this the default behavior of parse? Or why isn't there at least some sort of a typedParse function built into the library?
I'm sure this has been raised before, but I couldn't find a satisfying answer. Since the input argument of
parse(input: unknown), is of typeunknown, theparsemethod can accept anything and guarantee the type of the output. However, in many cases, this seems to sidestep the whole point of typescript, turning what would be compile-time errors into runtime errors. Consider this example:In this case above, we'd be better of without zod at all, since adding the
parsemethod obfuscates the compile-time error. In this simple example, raw typescript is preferable, but one might imagine wanting to use some features of zod, liketransformor the fact thatpassthroughis false by default to have more precise control over which properties come out of the function.We can build a function like this: which I think would do everything we want, getting us both the power of
zodand the power of standard compile-time type checking.The question is, why isn't this the default behavior of
parse? Or why isn't there at least some sort of atypedParsefunction built into the library?