Add castBoolean #236
MarlonPassos-git
started this conversation in
Ideas
Replies: 1 comment 1 reply
-
If it only accepts a If we wanted it to be a “better As far as implementation goes, here's my proposal: function parseBoolean(str: string): boolean | undefined {
const match = /^(?:(1|true)||0|false)$/i.exec(str)
return match && match[1] !== undefined
} It returns…
You can use the parseBoolean(str) ?? true You can use type assertion for non-string inputs (though it's not recommended): parseBoolean(true as any) // => true
parseBoolean(false as any) // => false
parseBoolean(1 as any) // => true
parseBoolean(0 as any) // => false
parseBoolean(-0 as any) // => false, because String(-0) === "0"
parseBoolean(-1 as any) // => null
parseBoolean(null as any) // => null
parseBoolean(undefined as any) // => null |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Recently, I encountered an issue while parsing environment variables in a project where the values could come in different forms, such as "True", "true", "", "FALSE", "false", etc. The task was simple: convert these values into booleans consistently. At that moment, I recalled the ParseBool function from Go, which handles this kind of conversion perfectly.
I believe a similar function could be a valuable addition to Radashi. It would provide a standardized and reliable way to handle such conversions.
Interestingly, I found a Zod issue requesting a similar feature, which highlights the necessity and utility of such a feature in libraries dealing with data validation and parsing.
it would be an adaptation for Boolean()
I'm open to other name suggestions
Beta Was this translation helpful? Give feedback.
All reactions