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?
In Haxe, you'd usually use Std.is()
for this instead of Type.typeof()
:
if (Std.is(param, Array)) {
trace('param is Array');
} else if (Std.is(param, 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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With