vendredi 8 mai 2020

Typescript - String to type

I have a class Message representing some data. Every message share the same header. However, depending on the type of message, they have different payloads. For example:

class Message {
  serial: string
  length: number
}

class LKMessage extends Message {}

class UDMessage extends Message {
  location: Location
}

The problem here is that I don't know the message type. The user just says "post a message", and sends the type along with the data. I could potentially create a different post function for every type of message, but I would write the same code a lot.

I tried something like this:

interface MessagePayload {}

interface LKMessagePayload extends MessagePayload {}

interface UDMessagePayload extends MessagePayload {
  location: Location
}

class Message<T extends MessagePayload> {
  serial: string
  length: number
  payload: T
}

The problem is instantiation: the user sends the type as a string, so I can't just write new Message<type>(data). I thought of using reflection, but I couldn't get it to work.





Aucun commentaire:

Enregistrer un commentaire