From 49081fd49b1763e4970f7a75fca0f54b04e1f2b1 Mon Sep 17 00:00:00 2001 From: Ben Tefay Date: Wed, 11 May 2022 20:48:48 +1000 Subject: [PATCH] Add documentation about transform taking ctx --- README.md | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index e21c40c8da..ace3bc4262 100644 --- a/README.md +++ b/README.md @@ -1604,7 +1604,27 @@ const stringToNumber = z.string().transform((val) => myString.length); stringToNumber.parse("string"); // => 6 ``` -> ⚠️ Transform functions must not throw. Make sure to use refinements before the transform to make sure the input can be parsed by the transform. +> ⚠️ Transform functions must not throw. Make sure to use refinements before the transform or addIssue within the transform to make sure the input can be parsed by the transform. + +#### Validating during transform + +Similar to `superRefine`, `transform` can optionally take a `ctx`. This allows you to simultaneously +validate and transform. Make sure to return a value of the correct type otherwise the inferred type will include `undefined`. + +```ts +const Strings = z + .string() + .transform((val, ctx) => { + const parsed = parseInt(val); + if (isNaN(parsed)) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: "Not a number", + }); + } + return parsed; + }); +``` #### Chaining order