Search code examples
typeshaxe

Haxe: check if a dynamic type is an Object


I need to check if var a : Dynamic = {} is an object. So I'm expecting:

var a : Dynamic;
a = 17.2; check( a ); // false
a = "test"; check( a ); // false
a = [1,2,3]; check( a ); // false
a = 99; check( a ); // false
a = {b:1, c:2}; check( a ); // true

Here is what I have (slightly different from above, as it checks for multiple types and returns an enum). It all works, except the object line:

function check( v : Dynamic ) : TokenType {
    if ( Std.is(v, std.Array) ) return TTArray;
    else if ( Std.is(v, std.String) ) return TTString;
    else if ( Std.is(v, Object) ) return TTObject; // What do I need here?
    else if ( Math.isNaN( v ) ) return TTUnknown;
    else if ( Std.is(v, StdTypes.Float) ) return TTNumber;
    else if ( Std.is(v, StdTypes.Int) ) return TTNumber;
    return TTUnknown;
}

Note - this is tiny snippet of a much larger class. The type has to be Dynamic (I can't use Any for example).

Thanks in advance!


Solution

  • You have two options here:

    The former may be a bit more reliable for your use case, since classes are a separate ValueType. For instance, on the JS target Type.typeof("string") will result in TClass(String), while you simply get true with Reflect.isObject().