如何检查Haxe中参数的类型
How to check the type of a parameter in Haxe
我正在将 JavaScript 库转换为 Haxe。
感觉haxe和js很像,但是在工作中遇到了函数覆盖的问题
例如,在下面的函数中 param
可以是整数或数组。
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');
}
}
哈克斯:
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');
}
}
当然 Haxe 支持 Type.typeof()
但 Array
没有任何 ValueType
。我该如何解决这个问题?
在 Haxe 中,您通常会使用 Std.is()
而不是 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');
}
也可以使用 Type.typeof()
,但不太常见 - 您可以使用 pattern matching for this purpose. Arrays are of ValueType.TClass
,它有一个 c:Class<Dynamic>
参数:
switch (Type.typeof(param)) {
case TClass(Array):
trace("param is Array");
case TInt:
trace("param is Int");
case _:
trace("unknown type");
}
我正在将 JavaScript 库转换为 Haxe。 感觉haxe和js很像,但是在工作中遇到了函数覆盖的问题
例如,在下面的函数中 param
可以是整数或数组。
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');
}
}
哈克斯:
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');
}
}
当然 Haxe 支持 Type.typeof()
但 Array
没有任何 ValueType
。我该如何解决这个问题?
在 Haxe 中,您通常会使用 Std.is()
而不是 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');
}
也可以使用 Type.typeof()
,但不太常见 - 您可以使用 pattern matching for this purpose. Arrays are of ValueType.TClass
,它有一个 c:Class<Dynamic>
参数:
switch (Type.typeof(param)) {
case TClass(Array):
trace("param is Array");
case TInt:
trace("param is Int");
case _:
trace("unknown type");
}