首页 > 解决方案 > Typescript - 具有数据模型接口的多态性

问题描述

我想我在这里寻找一种设计模式。这是我所拥有的 -

应用程序.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;
}

表示传入数据的非常简单的模型,没什么特别的。

现在我有一个服务,它可以调用 API 并将数据获取为IApp.

应用程序.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;
}

然后我appsService.appiOSVersionApple组件和组件appsService.appAndroidVersion中使用AndroidApple和组件都有Android不同的逻辑。我尝试appsService.appVersion在每个组件中使用,但由于它是基本IApp类型,因此该对象没有特定于平台的属性;所以必须使用两个不同的变量。

我的问题:是否可以appsService.appVersion在组件AppleAndroid组件中重用?(我需要这个变量来apps.service.ts进行状态管理)。拥有两个不同的变量并不疯狂,对吧?

如果这没有意义,请道歉。如果您需要更多详细信息,请告诉我。

提前谢谢了!

标签: typescriptinterfacepolymorphism

解决方案


你在什么时候设置this.appVersion.platform变量?你appService能用一个通用的参数化你的 fetch 调用,appsService.fetch<T>当你调用它时,用你的平台特定接口参数化它吗?

这样,如果您执行以下操作: appService.fetch<IAppleApp>(...) 您可以将返回类型设为泛型T并访问该接口的结构。


推荐阅读