How to convert a bool to string

How to convert a bool to a string? Struggling. I tried: Hey it's a bool: ${myBool}, but no dice. I’ve looked in Js.String, and Belt, but didn’t see a bool to string.

… yes, I could use pattern matching, but really?

switch authResponse {
| true => log(`verifyJWT, validated JWT, authResponse: true`)
| false => log(`verifyJWT, validated JWT, authResponse: false `)
}

You can use the polymorphic Js.String.make, which compiles to the String() function in JS.

log(`verifyJWT, validated JWT, authResponse: ${Js.String.make(authResponse)}`)

4 Likes

There is no Rescript API to do it.
But you can do it in many ways.

Maybe a binding to String:

module Bool = {
  @val external toString: (bool) => string = "String"
}

let bool = true
let string = bool->Bool.toString
5 Likes

string_of_bool is a part of Pervasives. You can just use it, e.g.

let x = true;
let y = string_of_bool(x);
let z = `y = ${y}`;

There’s a bunch of other helpers like this that are available, e.g. string_of_int, string_of_float (interestingly using this triggers a warning suggesting the use of Js.Float.toString instead), int_of_float, and float_of_int. All of these come from OCaml which ReScript is based on.

7 Likes

Thanks for the help everyone!

So Kevin, I swore I’ve seen some of these accidentally popup in code hints sometimes in VSCode. I think Yawar pointed me to where these things are documented before, but I lost it. Was it OCAML docs or something else? I feel like I’m missing out on a lot of functions I should be reading about.

Pervasives aren’t documented well, but you can find a list of all of them in https://github.com/rescript-lang/rescript-compiler/blob/master/lib/es6/pervasives.js.

1 Like

This can work but ReScript doesn’t have full template strings. The syntax is slightly different when the variable needs to be coerced into a string:
https://rescript-lang.org/try?code=DYUwLgBAtgngQgewcCBeCYBOBXEAoAKQGcA6YBAcwAoArAAwAkQYIBLMAciIgEMIAjJMABcEACSxEyOgEogA

1 Like

Yeah because the OCaml inherited stdlib is supposed to be disabled by default in the future, as stated in the Roadmap for v10 (but will be accessible via flag for those who need it).