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?

>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

Leave a Reply