distante
distante

Reputation: 7005

typescript: how to overload a function of an interface in another interface that extends the first one

I am working on a Capacitor plugin and I need to define possible event listeners.

The old implementation of the plugin had one big interface with all the possible listeners in the same file like:

export interface Plugin {
 
 addListener(
    eventName: 'bannerShow',
    listenerFunc: (info: any) => void,
  ): PluginListenerHandle;

 addListener(
    eventName: 'bannerHide',
    listenerFunc: (info: string) => void,
  ): PluginListenerHandle;

 addListener(
    eventName: 'rewardShow',
    listenerFunc: (info: SomeInterface) => void,
  ): PluginListenerHandle;

 addListener(
    eventName: 'rewardHide',
    listenerFunc: (info: string) => void,
  ): PluginListenerHandle;

}

I am separating that so it is easier to mantain, in this way:

export interface Plugin extends Banner, Reward {
  // General plugin calls here
}

// Other file
export interface Banner {

specificBannerFunction(): void;

addListener(
    eventName: 'bannerShow',
    listenerFunc: (info: any) => void,
  ): PluginListenerHandle;

 addListener(
    eventName: 'bannerHide',
    listenerFunc: (info: string) => void,
  ): PluginListenerHandle;
}

// Other file
export interface Reward {

 specificRewardFunction(): string;
 addListener(
    eventName: 'rewardShow',
    listenerFunc: (info: SomeInterface) => void,
  ): PluginListenerHandle;

 addListener(
    eventName: 'rewardHide',
    listenerFunc: (info: string) => void,
  ): PluginListenerHandle;
}

The problem is that Typescript says:

Interface 'Plugin' cannot simultaneously extend types 'Banner' and 'Interstitial'. Named property 'addListener' of types 'Banner' and 'Interstitial' are not identical

how can let typescript know I am overloading that function call?

Upvotes: 0

Views: 534

Answers (1)

Dan Fletcher
Dan Fletcher

Reputation: 1228

Still pretty new to TS myself so I don't know if you can do this with Interfaces or not but if you change your Plugin interface to a type you can use an intersection.

For example instead of:

export interface Plugin extends Banner, Reward {
  // General plugin calls here
}

You could do:

export type Plugin = Banner & Reward & { /* General plugin calls here */ }

Upvotes: 2

Related Questions