Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a cleaner way to write variations of a type in Typescript?

I would like to have different variations of content type with subtypes (text, photo etc) having common properties like id, senderId, messageType, contentData.

  • messageType will always be fixed for each subtype, and contentData properties changes depending on messageType

  • Then I intend to use IContent within the app, which will infer properties of contentData after defining messageType

    MEDevel.com: Open-source for Healthcare and Education

    Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

    Visit Medevel

  • I assume there will be many other content subtypes and more common properties yet to be added

Is this the better way to write this to avoid having many duplicated properties (eg id, senderId)? (maybe with generics or creating a base type and then extending?)

interface IContentText {
  id: string;
  senderId: string;
  messageType: 'TEXT';
  contentData: {
    text: string;
  };
}

interface IContentPhoto {
  id: string;
  senderId: string;
  messageType: 'PHOTO';
  contentData: {
    url: string;
    caption: string;
  };
}

export type IContent = IContentText | IContentPhoto;

>Solution :

You can indeed use a base interface to save repetition

interface IContentBase{
   id: string;
  senderId: string;
  messageType: 'TEXT'|'PHOTO';
}
interface IContentText extends IContentBase {
  messageType: 'TEXT';
  contentData: {
    text: string;
  };
}

interface IContentPhoto  extends IContentBase{
  messageType: 'PHOTO';
  contentData: {
    url: string;
    caption: string;
  };
}

export type IContent = IContentText | IContentPhoto;


const thing:IContent ={id:'1',senderId:'123', messageType:'TEXT',contentData:{text:'123'}}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading