[Tutorial] Get the Type Name, not Type Value

Just recently fixed a bug in my engine trying to figure out why the Type.typeof() comparison didn’t work, and then realised something.

In languages like C#, typeof() returns that actual type name of the type you want to get, so for example:

object myObject = someLabel;
object otherObject = someForm;

myObject.GetType() //Returns "Label"
otherObject.GetType() //Returns "Form"

In Haxe, the above similar example would instead look something like this:

var myObject:Dynamic = someLabel;
var otherObject:Dynamic = someForm;

Type.typeof(myObject); //Returns "TClass"
Type.typeof(otherObject); //Returns "TClass"

The Haxe typeof() function only gets the base type, not the name of the type you are actually looking for, which may in this case be “Label” or “Form”.

In order to achieve this in Haxe, you would need to do this:

Type.getClassName(Type.getClass(myObject)); //Returns "Label"

And thus, this function was born:

package utils;

class Misc
    public static function getTypeName(obj:Dynamic):String
        if (Type.typeof(obj) == ValueType.TEnum)
            return Type.getEnumName(Type.getEnum(obj));
        else if (Type.typeof(obj) == ValueType.TClass)
            return Type.getClassName(Type.getClass(obj));
            return "";

Which should be the result you want anyway when comparing types. As the Haxe API states:

Returns the runtime type of value v.
The result corresponds to the type v has at runtime, which may vary
per platform.
Assumptions regarding this should be minimized to avoid surprises.

That last bit says pretty much anything you need to know.