valibot icon indicating copy to clipboard operation
valibot copied to clipboard

feat: create coercion actions for primitives (and date)

Open EskiMojo14 opened this issue 6 months ago • 3 comments

Decisions left:

  • should we try/catch around conversions? it's rare but some can throw, like Number(Symbol())
  • v.toNumber - should we check for NaN after converting, or recommend piping into v.number?
  • v.toDate - similarly, should we check the date is valid, or recommend piping into v.date?

EskiMojo14 avatar May 31 '25 20:05 EskiMojo14

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
valibot ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 16, 2025 6:43pm

vercel[bot] avatar May 31 '25 20:05 vercel[bot]

Thank you so much!

should we try/catch around conversions? it's rare but some can throw, like Number(Symbol())

Yes, we should do that whenever it is necessary to cover all edge cases

v.toNumber - should we check for NaN after converting, or recommend piping into v.number? v.toDate - similarly, should we check the date is valid, or recommend piping into v.date?

I would only convert it. Do you know what Zod is doing here?

fabian-hiller avatar Jun 01 '25 00:06 fabian-hiller

with Zod the coercion isn't separate from the schema (it just happens as the first step of the schema if configured), so z.coerce.number() would be the same as v.pipe(v.unknown(), v.toNumber(), v.number())

EskiMojo14 avatar Jun 01 '25 00:06 EskiMojo14

Open in StackBlitz

npm i https://pkg.pr.new/valibot@1212

commit: 6f32684

pkg-pr-new[bot] avatar Nov 21 '25 01:11 pkg-pr-new[bot]

I will start working on this PR to get it over the line

fabian-hiller avatar Nov 21 '25 01:11 fabian-hiller

v.toNumber - should we check for NaN after converting, or recommend piping into v.number? v.toDate - similarly, should we check the date is valid, or recommend piping into v.date?

I decided to return an issue for both as I think that this is the happy path for most users.

Feel free to review my changes.

fabian-hiller avatar Nov 21 '25 03:11 fabian-hiller

I will finalize and merge this PR in the next days

fabian-hiller avatar Nov 21 '25 04:11 fabian-hiller

changes look good, thank you 😄

EskiMojo14 avatar Nov 21 '25 10:11 EskiMojo14

v1.2.0 is available

fabian-hiller avatar Nov 24 '25 23:11 fabian-hiller