Skip to content

Commit

Permalink
Merge pull request #948 from EltonLobo07/doc/improve-optionals-guide
Browse files Browse the repository at this point in the history
improve `optionals` guide
  • Loading branch information
fabian-hiller authored Dec 5, 2024
2 parents 65f0e59 + bbdbc90 commit 42d6125
Showing 1 changed file with 9 additions and 8 deletions.
17 changes: 9 additions & 8 deletions website/src/routes/guides/(schemas)/optionals/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ description: >-
contributors:
- fabian-hiller
- fartinmartin
- EltonLobo07
---

import { Link } from '@builder.io/qwik-city';
Expand Down Expand Up @@ -47,8 +48,8 @@ import * as v from 'valibot';

const OptionalStringSchema = v.optional(v.string(), "I'm the default!");

type OptionalStringInput = v.Input<typeof OptionalStringSchema>; // string | undefined
type OptionalStringOutput = v.Output<typeof OptionalStringSchema>; // string
type OptionalStringInput = v.InferInput<typeof OptionalStringSchema>; // string | undefined
type OptionalStringOutput = v.InferOutput<typeof OptionalStringSchema>; // string
```

By providing a default value, the input type of the schema now differs from the output type. The schema in the example now accepts `string` and `undefined` as input, but returns a string as output in both cases.
Expand All @@ -70,17 +71,17 @@ The previous example thus creates a new instance of the [`Date`](https://develop
In rare cases, a default value for an optional entry may depend on the values of another entries in the same object. This can be achieved by using <Link href="/api/transform/">`transform`</Link> in the <Link href="/api/pipe/">`pipe`</Link> of the object.

```ts
import * as v from 'valibot';

const CalculationSchema = v.pipe(
v.object({
a: v.number(),
b: v.number(),
sum: v.optional(v.number()),
}),
v.transform((input) => {
if (input.sum === undefined) {
return { ...input, sum: input.a + input.b };
}
return input;
})
v.transform((input) => ({
...input,
sum: input.sum === undefined ? input.a + input.b : input.sum,
}))
);
```

0 comments on commit 42d6125

Please sign in to comment.