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

How can I duplicate a TypeScript interface but change the property type in the duplication?

I have the following interfaces which are very similar but have different property types:

export interface ChannelOverlayStyles {
    bigChannelLogoWrapper: ViewStyle;
    bigPackshotChannelLogo: ViewStyle;
    channelLogo: ViewStyle;
    channelPackshotGradient: ViewStyle;
    smallChannelLogoWrapper: ViewStyle;
    portraitLogo: ViewStyle;
    landscapeLogo: ViewStyle;
}

 export interface ChannelOverlayStylesWeb {
    bigChannelLogoWrapper: ViewStyleWeb;
    bigPackshotChannelLogo: ViewStyleWeb;
    channelLogo: ViewStyleWeb;
    smallChannelLogoWrapper: ViewStyleWeb;
    portraitLogo: ViewStyleWeb;
    landscapeLogo: ViewStyleWeb;
 }

Is there away I can avoid duplicating these by creating a type that duplicates the first interface but replaces the property type automatically?

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

>Solution :

You can abstract the common types to a base interface that is generic over the field type. While limiting the generic field type to only ViewStyleWeb | ViewStyle


export interface ChannelOverlayBase<View extends ViewStyleWeb | ViewStyle> {
    bigChannelLogoWrapper: View;
    bigPackshotChannelLogo: View;
    channelLogo: View;
    smallChannelLogoWrapper: View;
    portraitLogo: View;
    landscapeLogo: View;
 }

export type ChannelOverlayStyles = ChannelOverlayBase<ViewStyle> & {channelPackshotGradient: ViewStyle}

export type ChannelOverlayStylesWeb = ChannelOverlayBase<ViewStyleWeb>;

Typescript Playground

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