arrayshaxe

How to check the type of a parameter in Haxe


I'm converting a JavaScript library to Haxe. It seems Haxe is very similar to JS, but in working I got a problem for function overwriting.

For example, in the following function param can be an an integer or an array.

JavaScript:

function testFn(param) {
    if (param.constructor.name == 'Array') {
        console.log('param is Array');
        // to do something for Array value
    } else if (typeof param === 'number') {
        console.log('param is Integer');
        // to do something for Integer value
    } else {
        console.log('unknown type');
    }
}

Haxe:

function testFn(param: Dynamic) {
    if (Type.typeof(param) == 'Array') { // need the checking here
        trace('param is Array');
        // to do something for Array value
    } else if (Type.typeof(param) == TInt) {
        trace('param is Integer');
        // to do something for Integer value
    } else {
        console.log('unknown type');
    }
}

Of course Haxe supports Type.typeof() but there isn't any ValueType for Array. How can I solve this problem?


Solution

  • In Haxe, you'd usually use the is operator for this instead of Type.typeof(). Behind the scenes, the operator uses Std.isOfType().

    if (param is Array) {
        trace('param is Array');
    } else if (param is Int) {
        trace('param is Integer');
    } else {
        trace('unknown type');
    }
    

    It's possible to use Type.typeof() as well, but less common - you can use pattern matching for this purpose. Arrays are of ValueType.TClass, which has a c:Class<Dynamic> parameter:

    switch (Type.typeof(param)) {
        case TClass(Array):
            trace("param is Array");
        case TInt:
            trace("param is Int");
        case _:
            trace("unknown type");
    }