zod icon indicating copy to clipboard operation
zod copied to clipboard

`z.custom<T>()` documentation missing.

Open arstnei0 opened this issue 1 year ago • 3 comments

Sometimes we just want the type inferences, but not checking them.

The z.as<T>() can give you the ability to still use the Type inference but you don't need to change the T also to a Zod object.

For example, we can use it like this:

const HandleFuncZod = z.any().as<(
	req: IncomingMessage,
	res: ServerResponse
) => void>()
type HandleFunc = z.infer<typeof HandleFuncZod>

Because we are not able to transform the IncomingMessage and ServerResponse into zod objects and we actually don't need to do that. This is nice hook in many cases.

The checking process is still available. For example:

const TaskZod = z.object({
	id: z.string()
}).as<{
	content: TaskContent,
	id: string
}>()
type Task = z.infer<typeof TaskZod>

Zod will still check the object being passed to the .parse() function by this: z.object({ id: z.string() }). But the type Task is being inferred as { content: TaskContent, id: string }.

This feature is providing a nice flexibility. Before this, we can probably only use Zod in some data checks because there are many datas that don't need to be checked and types that can't be used in Zod (e.g. the IncomingMessage in the http module) (or using them for the entire app with a bunch of trivial tricks). But after this, Zod can be used in the whole app.

arstnei0 avatar Dec 05 '22 12:12 arstnei0

This sort of exists but is undocumented...whoops.

const schema = z.custom<{
	content: TaskContent,
	id: string
}>();

This runs no validation checks on the input, but the inferred type is whatever you've passed as the generic.

There's no equivalent of the .as() method but I'm not sure I like it. Seems like it will be less duplicative and less verbose to just use z.custom inside your object schema:

const TaskZod = z.object({
	id: z.string(),
        content: z.custom<TaskContent>()
});
type Task = z.infer<typeof TaskZod>

colinhacks avatar Dec 05 '22 20:12 colinhacks

Oh, thanks.

arstnei0 avatar Dec 05 '22 23:12 arstnei0

The feature is missing in the documentation.

Should we add it into the doc now? Or is it still not stable?

arstnei0 avatar Dec 05 '22 23:12 arstnei0

Is this what you are looking for? https://github.com/colinhacks/zod#custom-schemas

JacobWeisenburger avatar Dec 26 '22 14:12 JacobWeisenburger

Is this what you are looking for? colinhacks/zod#custom-schemas

Oh, I finnally found that.

arstnei0 avatar Dec 27 '22 00:12 arstnei0