Multiple types for a value


Is it possible to have a value that has multiple Stimulus types? How to do ?

My value preload is both a boolean and a string.


export default class extends Controller {
    static values = {
        preload: String, (String|Boolean ?)

What does it mean for it to be both a boolean and a string? Surely the value of the string means something, right? It’s not a pure binary yes/no or true/false (or if you believe in the three-state boolean, then true/false/unset).

Now I could see that you might have a string, and if that string is empty, then it could be seen as the boolean false, and if it is valued with anything, then it would also be the boolean true, but in and of itself, it is still a string, and its value has meaning beyond that rather squinty view. You may also agree on a scheme where a string may be Y and that means the boolean true, or N, and that means the boolean false. In that case, you are basically doing the same thing as many database engines when it comes to representing the concept of a boolean.

If you were working in Ruby (with Rails for the extra bits), you might write something like this:

attribute :name, :string

def name?

I am sure you can write something equivalent in JavaScript. But the idea to get across is that name? is not the same thing as name. You will always get a true/false value out of the former, while the latter can be an empty string or some number of characters, and those characters have meaning outside of their mere existence.

So in your specific example, it seems to me that you want to represent the concept of “is this preloaded?” along with “here is the preloaded value” in one variable. I would not try to declare one variable with both of those semantics.


Value is both a boolean and a string, for instance option preload for Tom Select.

Are you trying to model the way that (in HTML5) some attributes don’t require a value, like checked or disabled? Where the existence of the attribute at all signals that it is “true”? That’s obviously not the case for other attributes, where their value has significance in a boolean sense, like autocomplete="no".

I still maintain that within your JavaScript, unless you are directly getting these kinds of attributes from a DOM element (and honestly, even if you do), you would need to have a shadow method to compare it with its “truthy” value and return the boolean equivalent.

I doubt sincerely that you will be able to apply both the boolean and string types to the variable itself.