ianstormtaylor / superstruct

A simple and composable way to validate data in JavaScript (and TypeScript).
https://docs.superstructjs.org
MIT License
7.01k stars 224 forks source link

Example coercion does not work. Have I done it right ? #1175

Closed houd1ni closed 1 year ago

houd1ni commented 1 year ago

Hi!

I read: https://docs.superstructjs.org/api-reference/coercions#custom-coercions I do:

const schema = object({
  x: coerce(number(), string(), (value) => +value)
})
console.log(schema.validate({x: '42'}))

I have:

[
   StructError: At path: x -- Expected a number, but received: "42",
   value: '42',
   type: 'number',
   refinement: undefined,
   key: 'x',
   path: [ 'x' ],
   branch: [ [Object], '42' ],
   failures: [Function (anonymous)]
 },
 undefined
]

What's wrong ? Thanx.

JoniJnm commented 1 year ago

Use the coerce option:

const schema = object({
  x: coerce(number(), string(), value => +value),
});
console.log(schema.validate({x: '42'}, {coerce: true}));
houd1ni commented 1 year ago

Thanks! Almost at the same time found it in the code tho 😄 . Obviously, needs some doc improvement for this. @ianstormtaylor