Closed chimame closed 1 month ago
The coerce
method has been removed because I felt it was an insecure API. In most cases, you don't want to coerce an unknown input into a specific data type. Instead, you want to transform a specific data type into another specific data type. For example, a string or a number into a date. To explicitly define the input type, we recommend using the new pipe
method together with the transform
action to achieve the same functionality.
// Before
const DateSchema = v.coerce(v.date(), (input) => new Date(input));
// After
const DateSchema = v.pipe(
v.union([v.string(), v.number()]), // <-- Select which input types to accept
v.transform((input) => new Date(input))
);
You can also accept unknown
to have the same behavior as with the older versions.
const DateSchema = v.pipe(
v.unknown()
v.transform((input) => new Date(input))
);
I always appreciate a quick response.
Using unknown
is a good workaround. I modified the code I presented in this way to get the expected behavior.
describe('sample', () => {
it('should throw an error when the string is empty', () => {
// When using version 0.30.0 of valibot
// const schema = coerce(string(), (value) => value === '' ? undefined : value)
// When using version 0.31.0-rc.1 of valibot
const schema = pipe(unknown(), transform((value) => value === '' ? undefined : value), string())
const result = safeParse(schema, '')
expect(result.success).toBe(false)
})
})
I will modify my library based on this code. Thank you so much for your response. I hope Valibot, a great library, will be more widely adopted.
First of all, I really like the library called valibot. I'm grateful to them for providing such a great library.
Overview
Reproduce the behavior of the
coerce
method with thepipe
methodDetails
The
coerce
method will be removed in 0.31.0. Therefore, I think that migrating thecoerce
method will be as follows, as written in the documentation.However, in the case of the
coerce
method, the transformation is performed before verification, so I believe that the correct migration behavior will match thecoerce
method if you can pass the transform to the first argument of thepipe
method.With the current implementation, it seems possible to execute it as long as you ignore the type. Please let me know if the migration method to 0.31.0 is incorrect.