export const NumberFromString = Schema.transformOrFail(
// Source schema: accepts any string
Schema.String,
// Target schema: expects a number
Schema.Number,
{
// optional but you get better error messages from TypeScript
strict: true,
decode: (input, options, ast) => {
const parsed = parseFloat(input)
// If parsing fails (NaN), return a ParseError with a custom error
if (isNaN(parsed)) {
return ParseResult.fail(
// Create a Type Mismatch error
new ParseResult.Type(
// Provide the schema's abstract syntax tree for context
ast,
// Include the problematic input
input,
// Optional custom error message
"Failed to convert string to number"
)
)
}
return ParseResult.succeed(parsed)
},
encode: (input, options, ast) => ParseResult.succeed(input.toString())
}
)
export const NumberFromString = Schema.transformOrFail(
// Source schema: accepts any string
Schema.String,
// Target schema: expects a number
Schema.Number,
{
// optional but you get better error messages from TypeScript
strict: true,
decode: (input, options, ast) => {
const parsed = parseFloat(input)
// If parsing fails (NaN), return a ParseError with a custom error
if (isNaN(parsed)) {
return ParseResult.fail(
// Create a Type Mismatch error
new ParseResult.Type(
// Provide the schema's abstract syntax tree for context
ast,
// Include the problematic input
input,
// Optional custom error message
"Failed to convert string to number"
)
)
}
return ParseResult.succeed(parsed)
},
encode: (input, options, ast) => ParseResult.succeed(input.toString())
}
)