Data format using interface?

I’m trying to replicate something I use in TypeScript in Haxe and am not getting very far.

What I want to do is set up an interface for a data format (the data is for a map), I then will have an array of these which I’ll build from.

But, Haxe doesn’t want to do it the way TS does, and, despite my searching/experimenting I’ve not got very far…

This is what I’m trying to do:

interface MapFormat{

            cols: Int;
        	rows: Int;
            tiles:Array<Int>;
            
        }



public var map1:Array<MapFormat> = [
			{
		
				rows: 3,
				cols: 3,
				tiles: [3,0,2, 
						4,2,2,
						1,4,2],
			
			},
			{
		
				rows: 3,
				cols: 3,
				tiles: [4,2,2,
						3,0,2, 
						1,4,2],
			
			},

… and so on

Hi charlie_says.

You can achieve this using a typedef:

typedef MapFormat = {
    cols: Int,
    rows: Int,
    tiles:Array<Int>
}
var map1:Array<MapFormat> = [{rows: 3, cols: 3, tiles: [3,0,2,4,2,2,1,4,2]},{rows: 3, cols: 3, tiles: [4,2,2,3,0,2,1,4,2]}];
1 Like

Thank you!!
But, quick follow up question. As my map builder is in a different class, how can I access the typedef.

If I try to import, it fails. If I don’t add it, it doesn’t recognise the type…

var map:Array<SliderMap> = Reflect.getProperty(Maps, "map"+1);	// type not found

“Fails” how exactly? A compiler or runtime error? Can you share a complete code example to reproduce it, perhaps using https://try.haxe.org/?

If you put it inside it’s own file (“module”) you can import it directly:

test/MyTypedef.hx

package test;

typedef MyTypedef = {
   a:Int,
   b:String
}
import test.MyTypedef;

If you include it in another module (alongside a class or other types), then you can import the whole module, or the typedef within the module, like this:

test/MyClass.hx

package test;

class MyClass {
    public function new () {}
}

typedef MyTypedef = {
    a:Int,
    b:String;
}
import test.MyClass;

or

import test.MyClass.MyTypedef;

Thanks @singmajesty - I was looking over what you’d written, when I realised I’d made the rookie error of not importing the Map Class…

Haha, no trouble. It happens :smiley: