【问题标题】:Typescript - Polymorphism with data model interfacesTypescript - 具有数据模型接口的多态性
【发布时间】:2019-11-25 18:50:57
【问题描述】:

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

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;
}

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

现在我有一个服务可以调用 API 并以 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;
}

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

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

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

非常感谢!

【问题讨论】:

    标签: typescript interface polymorphism


    【解决方案1】:

    您在什么时候设置this.appVersion.platform 变量?您能否使用像 appsService.fetch<T> 这样的泛型参数化您的 appService 的 fetch 调用,并在调用它时使用您的平台特定接口对其进行参数化?

    如果你这样做的话: appService.fetch<IAppleApp>(...) 您可以将返回类型设为通用 T 并访问该接口的结构。

    【讨论】:

    • 泛型!我在我的 C# API 中使用了大量这些,但在 TypeScript 中并没有引起我的注意。非常感谢您的提示 :)(最近开始玩 Angular)
    猜你喜欢
    • 2019-07-03
    • 2021-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-28
    • 1970-01-01
    相关资源
    最近更新 更多