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

Time:08-03

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

  • 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;

CodePudding user response:

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'}}
  • Related