Exploring Polymorphism in Typescript through Data Model Interfaces

Seeking out a design pattern for the following scenario:

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

Basic models representing incoming data.

A service makes API calls and fetches 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;
}

Utilizing appsService.appiOSVersion in the Apple component, and appsService.appAndroidVersion in the Android component with separate logic for each. Attempted to use appsService.appVersion in both components, but lacking platform-specific properties forced the use of two variables.

Question: Can appsService.appVersion be reused in both Apple and Android components? Need this variable for state management within apps.service.ts. Using multiple variables isn't unreasonable, correct?

If unclear, please request more details.

Thank you!

Answer №1

When do you assign a value to the this.appVersion.platform variable? Is it possible to make the fetch call of your appService more generic by using something like appsService.fetch<T> and passing in the platform-specific interface when calling it?

By doing this:

appService.fetch<IAppleApp>(...)
You can set the return type as the generic T and access the structure of that interface.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What causes a Typescript error when attempting to escape a newline character?

My approach is quite simple: I concatenate multiple strings and format them to make them more readable. info() { return "x: " + this.xpos.toString() + "\n" \ + "y: " + this.ypos.t ...

Tips for resolving TypeScript object undefined error when utilizing object of model classes

I encountered an issue while working with an object of a class that retrieves data from an API. When trying to access this object in the HTML, I'm receiving error TS2532. Here is the relevant code snippet-- export interface TgtInfo{ Mont ...

Encountering an issue while attempting to incorporate an interface within a class in TypeScript

Can someone please help me figure out what I'm doing wrong? I'm attempting to implement an interface inside a class and initialize it, but I keep encountering this error: Uncaught TypeError: Cannot set property 'name' of undefined at n ...

Validate that the input is an array

Looking for a way to determine if a function parameter is an array or not, and then process it accordingly. If the parameter is not an array, convert it into an array before performing the desired function. For example: interface employee { first: st ...

Avoid unnecessary re-rendering of React Native components with each update of the state

I need my component to display either A or B based on the user's proximity to a specific location. I developed a custom hook to determine if the user is nearby. However, I'm facing an issue where the hook constantly returns a new value of true, ...

Is it Control or ControlGroup in Angular 2 - How to tell the difference?

let aa = this._formBuilder.control(""); let bb = this._formBuilder.group({ aa: aa }; I am trying to achieve the following: if (typeof(aa) == "Control") { // perform a specific action } else if (typeof(aa) == "ControlGroup") { // perform anoth ...

Encountering an error in Angular 8 with the plugin: Unhandled ReferenceError for SystemJS

I recently followed a tutorial on integrating plugins into my Angular application at this link. I'm trying to create a component in my Angular app that can execute and display an external component. However, I encountered the following error: Uncaugh ...

What's the process for validating i18n dictionaries using TypeScript?

Is there a way to enforce type checking on existing keys within dictionaries in react-i18next? This means that TypeScript will provide warnings at compile time if a key does not exist. For example: Let's say we have the following dictionary: { "f ...

Accessing the ViewModel property of a parent component from the ViewModel of its child in Aurelia

Having a scenario with two distinct components: <parent-component type="permanent"> <div child-component></div> </parent-component> class ParentComponentCustomElement { @bindable public type: string = "permanent"; } clas ...

The issue of TypeError arising while invoking a method within TypeScript Class Inheritance

Currently, I am developing a Node.js application with TypeScript. In this project, I have a base controller class named BaseController and a derived controller called SettingController. The intention is for the SettingController to utilize methods from the ...

The error message encountered while using webpack with TypeScript and React is: "Unexpected token React.Component

I am currently working on setting up a project using webpack, typescript, and react. I have implemented babel to transpile my typscript/react code. However, when starting the development server, I encountered the following error: Module parse failed: Un ...

Does an async function get automatically awaited if called in a constructor?

I am currently working on updating some code due to a library upgrade that requires it to be made async. The code in question has a base class that is inherited by other classes, and I need to call some functions in the constructor that are now asynchronou ...

TypeORM Error: Trying to access property 'findOne' of an undefined object

I've been working on implementing TypeORM with Typescript, and I have encountered an issue while trying to create a service that extends the TypeORM repository: export class UserService extends Repository<User> { // ... other service methods ...

Tips for developing a personalized form validator for validating JSON data exclusively in Angular

Within my Angular application, there exists a reactive form that has a single control known as configJson, which is visually represented by a <textarea> element in the DOM. The primary goal is to validate this specific form control to ensure that it ...

The configuration of the property has not been declared (Error: <spyOnProperty>)

Imagine having a MenuComponent @Component({ selector: 'cg-menu', templateUrl: './menu.component.html', styleUrls: [ './menu.component.scss' ] }) export class MenuComponent implements OnInit { menu: MenuItem[]; isLog ...

The production build encountered an error after upgrading Angular due to a problem with document.documentElement.setAttribute not being recognized

Recently, I updated my application to Angular 16 and the upgrade was successful. The application is running smoothly without any issues. However, when I attempted to run the command for a production build, ng build --configuration=production I encountere ...

The frontend is not triggering the Patch API call

I am having trouble with my http.patch request not being called to the backend. This issue only occurs when I try calling it from the frontend. Oddly enough, when I tested it in Postman, everything worked perfectly. Testing the backend on its own shows t ...

Issues arise in Typescript single-page applications due to the use of application insights

Currently, I am developing a single-page HTML application using TypeScript in VSCode. Initially, the app was running smoothly without any errors or warnings. However, I decided to incorporate Azure Application Insight into the project. To integrate it, I ...

Best practice for importing ts files from an npm package

When faced with the need to divide a ts project into multiple repositories/packages for creating microservices, the challenge arises in combining these packages efficiently. Some packages are required in one microservice, others in another, and some in all ...

tips for concealing a row in the mui data grid

I am working on a data grid using MUI and I have a specific requirement to hide certain rows based on a condition in one of the columns. The issue is that while there are props available for hiding columns, such as hide there doesn't seem to be an eq ...