Invoking functions from an array of TypeScript union types

Within my Typescript array, I have two classes:

StripeCardModel | StripeBankModel

Both of these classes extend

StripePaymentModel

My goal is to locate a specific class within the array that can potentially contain instances of both classes. Once found, I intend to utilize the achAccountInterfaceObject function on that class, as it will be guaranteed to be an instance of StripeBankModel.

let bankPaymentMethod = this.user.stripePaymentMethods.find( paymentMethod => paymentMethod instanceof StripeBankModel );
if ( bankPaymentMethod ) {
    this.bankAccount = bankPaymentMethod.achAccountInterfaceObject;
}

However, I am encountering a compile time error in Typescript:

Property 'achAccountInterfaceObject' does not exist on type 'StripeCardModel | StripeBankModel'.
Property 'achAccountInterfaceObject' does not exist on type 'StripeCardModel'.

Is there a way to work with multityped arrays in Typescript without experiencing such errors?

I've faced similar issues with switch cases like

function abc() : Foo|Boo {
    switch ( a.constructor )
    {
        case "Foo":
            a.boo();

        case "Bar":
            a.doo();
    }
}

While striving for clean code, Typescript seems to impose limitations that hinder my progress. Breaking up the code into separate functions based on class doesn't seem ideal when dealing with classes that share a common inheritance or functionality.

Answer №1

If a more refined solution is not available, casting bankPaymentMethod may help to eliminate compiler errors.

this.bankAccount = (<StripePaymentModel>bankPaymentMethod).achAccountInterfaceObject;

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 is the best way to store a gridster-item in the database when it is resized or changed using a static function

Following some resize and drag actions on my dashboard, I aim to store the updated size and position of my altered widget in my MongoDB database. Even though the gridster library offers the ability to respond to draggable and resizable events, these events ...

Conceal or remove disabled years in Angular Material datepicker

I previously disabled years prior to 2018, but now I would like to hide or delete them. The year selection range currently starts from 1998, but it should begin at 2018 instead. Is there a way to display only 3-4 years instead of the current 24-year rang ...

Recently updated from Angular 9 to 14 and noticed a peculiar issue in the deployed app - all API calls seem to only reference the root or hosted URL in the request URL

After upgrading the application from angular 9 to angular 14, I encountered a network call issue. The application was successfully deployed via azure devops, but all network calls were directed to the host URL instead of the expected API endpoints. For exa ...

Utilizing async await allows for the sequential processing of one item at a time within a For loop

Async await has me stumped, especially when it comes to processing items in an array with a 1 second delay: handleArrayProcessing() { clearTimeout(this.timer); this.timer = setTimeout(() => { for (const ...

Utilize nested JSON Response as row data for ag-Grid in Angular 4

Just starting out with angular and working on a project where I need to display JSON data in a grid. I've opted for ag-grid. Here's the sample JSON response I'm receiving from a rest API: [ { "id": 64, "name": "Utopia", "language": ...

What responsibilities do the TypeScript configuration files assume once a Vue project has been created?

As a newcomer to Vue.js, I am curious about the function of the typescript configuration files that are created after generating a Vue project. Upon running the npm create vue@latest command and opting for the "Add Typescript?" and "Add Vue ...

The issue at hand is that web components within Angular are failing to register changes

I have created a custom element for a todo item using custom element js. I am using this custom element in an Angular file and able to pass properties. The issue I am facing is that whenever I add or delete a new item, it's not reflecting in the custo ...

Switching between dark and light mode in Angular Ionic

How do I create a toggle option for users to select between: Light | Dark | Auto Light or dark will change the appearance of the PWA, while 'Auto' will adjust based on the system's dark/light mode. I've attempted to implement this fo ...

What is the process for defining a series of tests for karma through code?

Currently, I am in the process of developing an Angular Test Explorer. The exciting part is that I can view all the tests and execute them collectively by leveraging the karma module as shown in this code snippet: public async runWithModule(): Promise&l ...

What causes error TS2339 to occur: The property 'classList' is not found on type 'never'

Currently, I am working on creating a basic component called "BackToTop" const BackToTop: React.FC = () => { const bttEl = useRef(null); function scrollHandler(): void { var bttHtmlEl: HTMLElement | null = bttEl.current; if (bttH ...

Issue: NG05105 - Unforeseen artificial listener detected @transform.start

Encountered an issue in my Angular 17 app using Angular Material during the execution of ng test: Chrome browser throws 'app-test' title error in the AppComponent with the following message: Error: NG05105: Unexpected synthetic listener @ ...

Reset combobox to its default value when a different event happens

In my Angular 6 application, I have a reusable/shared component for a dropdown as shown below: <shared-dropdown-list-payments [valuesArray]="cashAccountLoaded" [defaultString]="defaultFromString" (outputEvent)="fromAccount($event)" tosca-id=" ...

Updating the DOM after making changes with Maquette involves calling the `renderMaquette

In a previous discussion, I expressed my desire to utilize Maquette as a foundational hyperscript language. Consequently, avoiding the use of maquette.projector is essential for me. However, despite successfully appending SVG objects created with Maquette ...

Manipulate md-select options with Angular using setValue

My goal is to update a select option, but I'm having trouble getting it to work properly. When I use this.eventForm.controls.venue.setValue(event.venue.name);, the value of venue changes to match event.venue.name. However, the select option itself doe ...

Embracing PWAs with subdomains – seamless installation

One of my Progressive Web Applications (PWA) called app A contains a link to another app, app B. Initially, I hosted both apps on the same subdomain (for example: ) and everything worked perfectly - installing app A also installed app B. However, when I a ...

When using a ngForm, submitting the form is triggered each time an action button is clicked

I have a form with multiple buttons in my ngForm. Each button has a different action, such as changing the status used for *ngIf condition check. However, every time I click the Create or Upload button, the form is submitted again and a new record is creat ...

What sets template-driven and reactive forms apart in practice?

Exploring the Angular2 new Forms API has revealed two distinct approaches to forms: Template driven and reactive (model-driven) forms. I am curious about the real-world differences between these two methods, beyond just syntax. Which approach is more adva ...

How can I conceal an element upon page load using Ionic framework?

index.component.ts initialize() { // Execute necessary functions after loading this.index.ready().then(() => { if(this.index.is('core')){ // this.menu.enable(false, 'mobileOnlyPages'); }else{ ...

Having trouble getting Edge browser to identify embedded blob as a valid source URL within a video tag

Having trouble using a blob as the source for a video file. Works well on Chrome and Safari, but facing issues on Edge. This code is written in TypeScript with Angular 7. On Edge mobile, it seems like a broken link is displayed. private initVideoFromBlo ...

Incorporating EJS Statements in a Simple HTML Document along with TypeScript

Trying to comprehend a seed project for Angular 2 which is quite complex, something caught my attention in the index.html file that I can't explain. There seems to be ejs statements included: <!-- src/client/index.html --> <title><%= A ...