Skip to content

Commit

Permalink
Add documentation about transform taking ctx
Browse files Browse the repository at this point in the history
  • Loading branch information
bentefay committed May 11, 2022
1 parent b36cf43 commit 71a33c5
Showing 1 changed file with 21 additions and 1 deletion.
22 changes: 21 additions & 1 deletion README.md
Expand Up @@ -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

Expand Down

0 comments on commit 71a33c5

Please sign in to comment.