Search code examples
typescastingtype-conversionhaxe

How do I evaluate if a string is a number or boolean in Haxe?


Using Std.isOfType() returns false when I'm evaluating an int and bool like this:

Std.isOfType('123', Int); // returns false instead of true
Std.isOfType('true', Bool); // returns false instead of true

So what is the proper way to do it? I am always going to receive a String so I want to determine it's type.


Solution

  • Your provided code is returning false because you are passing a String data type, instead of the data types you are testing for.

    To correct this, you just have to pass the data directly to the isOfType method, shown below:

    Std.isOfType(123, Int); // returns true
    Std.isOfType(true, Bool); // returns true
    

    If you wanted to pass in a string (as you are currently), then you will just have to parse the string into the appropriate data type before testing, such as:

    Std.isOfType(Std.parseInt('123'), Int)
    

    From quickly reading the documentation, I don't see a way to parse a string boolean into an actual boolean.