Home > database >  Inheritence and Multi Model Interface
Inheritence and Multi Model Interface

Time:10-28

I am new to TypeScript and Angular.

So I have a model currently

export interface ActionBE {
  type: string;
  actionInfo: ActionInfoBE;
}

export interface ActionInfoBE {
  field_id: string;
  value: string;
}

Now, I need to implement multiple types of actions where the ActionInfo would have different structures. This is easy to do in Java with a Parent Class, and then Jackson just serializes it properly when we serialize to JSON.

Now what I want is

export interface ActionBE {
  type: string;
  actionInfo: ActionInfoBE; --------> This model could be either of below 2 based on `type` above.
}

export interface SetObjectValueActionInfoBE {
  field_id: string;
  value: string;
}

export interface SendEmailActionInfoBE {
  recipient_email_address: string;
  message: string;
}

CodePudding user response:

If you Want multiple type to be validate , you can use OR operator '|'

export interface ActionBE {
  type: string;
  actionInfo: ActionInfoBE | SetObjectValueActionInfoBE | SendEmailActionInfoBE; --------> This could check one of the above and satisfies the type
}

export interface SetObjectValueActionInfoBE {
  field_id: string;
  value: string;
}

export interface SendEmailActionInfoBE {
  recipient_email_address: string;
  message: string;
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

you could use generics:

export interface ActionBE<T = any> {
  type: string;
  actionInfo: T;
}
  • Related