Do TypeBox support String Boolean type or Boolean Type Coercion? #1067
-
So I'm currently playing around with Zod and TypeBox for loading and parsing an env into a variable that can be used later (e.g. const schema = z.object({
DEBUG: z.boolean({ coerce: true }),
}); and when given an env file of DEBUG="true" the resulting of meanwhile doing it in TypeBox const schema = Type.Object({
DEBUG: Type.Boolean({ ... }),
}); there's no option to allow such behaviour, and using
Which is working fine when I have all env in string, but now I add Is it possible to do it in TypeBox or is it the limitation/out of the scope of this project? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
@deanrih Hi, The Value.Convert() function will coerce a string const Environment = Type.Object({
DEBUG: Type.Boolean()
})
const R = Value.Convert(Environment, process.env) // will convert "true" to true if possible. However it's recommended you use Value.Parse for environment loading. TypeBox exposes quite a few low level Value operations for flexibility, but the Parse function internally implements all these operations in a standard way to process a value how you would expect. const Environment = Type.Object({
DEBUG: Type.Boolean({ default: false }) // default values supported with Parse
})
const R = Value.Parse(Environment, process.env) // will convert "true" to true if possible. I would have a go using Parse first. If you need custom environment variable processing, take a look at the TypeBox Parse implementation. This library encourages users to mix and match various components of the library to construct various pipelines for validation, the Parse function is a good place to start if you need that level of functionality. https://github.com/sinclairzx81/typebox#values-parse https://github.com/sinclairzx81/typebox/blob/master/src/value/parse/parse.ts#L44-L68 Hope this helps |
Beta Was this translation helpful? Give feedback.
@deanrih Hi,
The Value.Convert() function will coerce a string
"true"
into a booleantrue
. TypeBox treats this as an explicit call you need to make rather than via configuration on the type. The following loosely achieves this.However it's recommended you use Value.Parse for environment loading. TypeBox exposes quite a few low level Value operations for flexibility, but the Parse function internally implements all these operations in a standard way to process a value how you would expect.