Mr. Robot
Mr. Robot

Reputation: 1824

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?

Upvotes: 0

Views: 451

Answers (1)

Ikechukwu Eze
Ikechukwu Eze

Reputation: 3131

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

Upvotes: 2

Related Questions