-
-
Notifications
You must be signed in to change notification settings - Fork 201
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Improved coerce and transform #197
Comments
We can't do const IntegerSchema = coerce(
number([integer("Not an integer")]),
// ^ Output type
(input: string) => Number(input)
// ^ Input type
); But I see the point, that sometimes you want to validate the input, transform it and also validate the output. We should find an official solution for this. At the moment I am not sure if we should put it in Here is an example with const IntegerSchema = transform(
string(),
(input) => Number(input),
number([integer("Not an integer")])
); |
I like the idea of Currently, export function transform<TInputSchema extends BaseSchema, TOutput, TOutputSchema extends BaseSchema<unknown, TOutput>>(
inputSchema: TInputSchema,
action: (value: Input<TInputSchema>) => TOutput,
outputSchema?: TOutputSchema
): BaseSchema<Input<TInputSchema>, TOutput> {
return {
...inputSchema,
_parse(input, info) {
const result = inputSchema._parse(input, info);
if (result.issues) return result;
if (!outputSchema) return getOutput(action(result.output));
const output = outputSchema._parse(action(input), info);
return output.issues ? output : getOutput(output.output);
}
};
}
const toNumber1 = transform(string(), Number);
type ToNumber1In = Input<typeof toNumber1>;
// ^? string
type ToNumber1Out = Output<typeof toNumber1>;
// ^? number
console.log(toNumber1._parse("1.2")); // 1.2 = OK
console.log(toNumber1._parse(1)); // Error
console.log(toNumber1._parse("a")); // NaN = OK
const toNumber2 = transform(string(), Number, number([custom((input) => !isNaN(input), "Not a number")]));
type ToNumber2In = Input<typeof toNumber2>;
// ^? string
type ToNumber2Out = Output<typeof toNumber2>;
// ^? number
console.log(toNumber2._parse("1.2")); // 1.2 = OK
console.log(toNumber2._parse(1)); // Error
console.log(toNumber2._parse("a")); // Error |
Thank you for your feedback. I think that I will bring this feature with the next version. |
I have now examined the implementation. I noticed that the data type of the output does not need to be validated, since we already know it. So instead of passing an entire schema as a third argument, it should be sufficient to pass a pipeline. |
Improved in v0.19.0 |
As described in this discussion:
I think the above functions can be improved. With the following,
coerce
could accept an input type.And the following is a custom function called
ioTransform
which accepts both an input and output schemaThe text was updated successfully, but these errors were encountered: