typescript - 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.appiOSVersion
在Apple
组件和组件appsService.appAndroidVersion
中使用Android
。Apple
和组件都有Android
不同的逻辑。我尝试appsService.appVersion
在每个组件中使用,但由于它是基本IApp
类型,因此该对象没有特定于平台的属性;所以必须使用两个不同的变量。
我的问题:是否可以appsService.appVersion
在组件Apple
和Android
组件中重用?(我需要这个变量来apps.service.ts
进行状态管理)。拥有两个不同的变量并不疯狂,对吧?
如果这没有意义,请道歉。如果您需要更多详细信息,请告诉我。
提前谢谢了!
解决方案
你在什么时候设置this.appVersion.platform
变量?你appService
能用一个通用的参数化你的 fetch 调用,appsService.fetch<T>
当你调用它时,用你的平台特定接口参数化它吗?
这样,如果您执行以下操作:
appService.fetch<IAppleApp>(...)
您可以将返回类型设为泛型T
并访问该接口的结构。
推荐阅读
- sql - SQL Server 使用间隔记录从累积列计算每日值
- amazon-web-services - API Gateway 自定义标头不会持续存在
- express - 我的嵌套文档不显示,猫鼬,快递
- python - python中最近的时间戳
- python - 如何更改选择器以使网站显示登录而不是使用 selenium python 和 chromedriver 进行注册?
- react-native - 如何在反应本机抽屉中禁用或删除或隐藏项目选定空间
- html - 如何访问 Handlebars 中嵌套循环内的数据?
- sharepoint - SharePoint 新式页面无法正确加载
- azure - 为什么在 Azure 中尝试通过 ARM-Template 创建 VM 时会触发错误“不是有效的资源引用。(代码:InvalidParameter)”?
- reactjs - React Native Redux - 为什么我不能访问我的 redux 存储中的数据并显示它?