Casting from base type to extended

I’m retrieving packets from a websocket. Every packet will have a cmd member to designate what type of packet it is, but from there, each type of packet will contain different data, such as:

TextPacket {
  text:String
}

ConnectionRefusedPacket {
  errors:Array<String>
}

ItemsPacket {
  locations:Array<Int>
}

What would be the best way for me to cast from the base packet type to the extended type to properly access whatever additional data that specific packet contains?

Please let me know if you need me to clarify anything, or need more information.

I think I found a solution, after I realised I wasn’t thinking in Haxe.

  • Create typedefs for each individual type
  • Create an enum with every packet type, each with a parameter of the individual packet typedef
  • Receive the packet as a Dynamic
  • I know that cmd is guaranteed to be there and a string, so evaluate it
  • Push the packet into a processing queue using the enum
  • When the client is polled, it receives the data with the proper typedef structure

I haven’t tested this solution yet, but, if nothing else, VSCodium is no longer screaming dozens of errors at me.

1 Like