scorpion35
scorpion35

Reputation: 1084

Typescript - Polymorphism with data model interfaces

I think I am looking for a design pattern here. Here is what I have -

IApp.ts

export interface IApp {
   platform: PlatformEnum;
   version: string;
   islive: boolean;
   title: string;
   iconurl: string;
}

IAppleApp.ts

export interface IAppleApp extends IApp {
   buildversion: string;
   versionstatus: string;
   sku: boolean;
   category: string;
   accountid: string;
}

IAndroidApp.ts

export interface IAndroidApp extends IApp {
   versioncodes: string;
   track: string;
   rolloutpercentage: boolean;
   acccountname: string;
}

Pretty simple models to represent incoming data, nothing fancy.

Now I have a service which makes the API calls and fetches the data as IApp.

apps.service.ts

appVersion: IApp;
appiOSVersion: IAppleApp;
appAndroidVersion: IAndroidApp;

if (this.appVersion.platform === PlatformEnum.ios) {
   this.appiOSVersion = this.appVersion as IAppleApp;
} else if (this.appVersion.platorm === PlatformEnum.android) {
   this.appAndroidVersion = this.appVersion as IAndroidApp;
}

And then I use appsService.appiOSVersion in Apple component, and appsService.appAndroidVersion in Android component. Both Apple and Android components have different logic. I tried to use appsService.appVersion in each component, but as it's of the base IApp type, the object doesn't have platform-specific properties; so have to use two different variables.

My question: Is it possible to reuse appsService.appVersion in both Apple and Android components? (I need this variable to be in apps.service.ts for state management). Having two different variables is not crazy, right?

Apologies if this doesn't make sense. Please let me know if you need more details.

Many thanks in advance!

Upvotes: 0

Views: 349

Answers (1)

ehutchllew
ehutchllew

Reputation: 958

At what point are you setting the this.appVersion.platform variable? Could you parameterize the fetch call of your appService with a generic like appsService.fetch<T> and when you call it, parameterize it with your platform specific interface?

That way if you do something like this: appService.fetch<IAppleApp>(...) You could have the return type be the generic T and access that interface's structure.

Upvotes: 1

Related Questions