The { }
is not a Type itself, it’s an expression which represents an anonymous structure.
Let’s take a better example:
typedef NamedStructure = {
var name:String;
}
The above is just like the {}
expression, except now we are telling the Haxe compiler that our object can be identified with a given name, which is NamedStructure
.
The same code in an anonymous structure form is simply:
var someObject:Dynamic = {
name: "My Name",
}
var named:NamedStructure = {
name: "My Name",
};
Both of these examples will compile, except one is known at compile-time while the other isn’t. Dynamic
takes any expression, including objects, which are not known at compile-time.
The issue with a typedef
is that you have to set all defaults, because default values are not inferred by the compiler. However, on some targets, there are performance benefits to using a typedef
structure versus a real class.
To solve the default values issue with a typedef
, you can assign @:optional
to its member variables:
typedef NamedStructure = {
var name:String;
@:optional var type:Int;
}
Similar to the NamedStructure
example above, your test2
function is asking for a structure (or technically an empty structure), but this doesn’t make sense because what are you going to do with an empty structure?
Taking the example above, if we were to instead require specific types:
static function test2(o:{ name: String })
{
}
Now the Haxe compiler will require the object being passed in to be a structure taking the name
variable and assigning something to it. The empty structure case is not a real type, so I think Haxe may just be guessing it’s type or inferring the type in a way that is preventing certain values from being accepted.