Encountering a compilation error while trying to utilize a union type in a function parameter within an

As stated on https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html, it is recommended to utilize multiple types for a parameter in a function (refer to the union part)

/* OK */
interface Moment {
    utcOffset(): number;
    utcOffset(b: number|string): Moment;
}

However, I am encountering an issue with Angular indicating an unresolved variable for the following method:

isFooBar(fooBar: Foo|Bar){
   if(fooBar.isFoo){ // error here
       console.log("is foo");
   }
}

I have defined two classes as follows:

export class Foo {
  isFoo: boolean;
}

export class Bar {
  isBar: boolean;
}

Is there a mistake in how I am using it?

To view the code, visit StackBlitz

Answer №1

When working with a union parameter, you can only access the common members of both types. Since isFoo is not present in both types, it will not be accessible directly. One way to handle this scenario is by using an in type guard to check for the existence of the property.

export class Foo {
    isFoo: boolean;
}

export class Bar {
    isBar: boolean;
}

function isFooBar(fooBar: Foo | Bar) {
    if ('isFoo' in fooBar) {
        // fooBar is of type Foo at this point
        console.log("is foo " + fooBar.isFoo);
    } else {
        // fooBar is of type Bar at this point
        console.log("is bar " + fooBar.isBar);
    }
}

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

LightWeightChart: How do I incorporate a chart that resembles this style?

Is it possible to create a chart using lightweight-chart that includes two graphs sharing the same x-axis but with different values on the y-axis? Essentially, I want to have two panes in a single chart. Does anyone have suggestions or tips on how this c ...

Preventing long int types from being stored as strings in IndexedDB

The behavior of IndexedDB is causing some unexpected results. When attempting to store a long integer number, it is being stored as a string. This can cause issues with indexing and sorting the data. For instance: const data: { id: string, dateCreated ...

Typescript displays an error message when attempting to assign a list of string variants to a defined type

Encountering an interesting TS error in the code snippet below: interface Bar { pictureType: "X" | "Y" } interface RT { output: Bar[] } const func = (): RT => { const list = [{ pictureType: 'X', }] r ...

After running `npm uninstall -g angular-cli`, I thought I had successfully removed angular-cli from my system. To my surprise, when I checked `ng --

What's the deal here? I uninstalled angular-cli globally on my laptop by running npm uninstall -g angular-cli, and now it's gone. But on my desktop, I can still use ng --version even after removing angular-cli globally. Any idea what's ha ...

Creating a model for a different user involves several steps that can be easily

Recently, I have been working on a project involving user interactions such as following other users and viewing their content. Using technologies like Prisma, GraphQL, and Nexus, I decided to create a following model today. The model structure is as follo ...

Tips for uploading a file and submitting form data with Angular2, using [(ngModel)], and then storing the reference in MongoDB

Currently, I am working on a task page and I need to implement the functionality to upload a file along with the form submission to the NodeJs express server. @Component({ selector: 'tasks', template: `<div mdl class="mdl-grid demo-c ...

Issues with updating in Firebase real-time database using Angular 2 are not

I am currently working on a simple app that inserts new records into Firebase. Below the input field, the app lists the last 10 items in the database. ISSUE: I am facing a problem where I have to start inputting something in the input field or click on ...

The name 'withStyles' is nowhere to be found

import * as React from "react"; import Button from "@material-ui/core/Button"; import * as PropTypes from "prop-types"; import {WithStyles} from '@material-ui/core'; import "./App.css"; import PageTwo from "./components/PageTwo"; ...

I am completely baffled by the meaning of this Typescript error

In my code, there is a button component setup like this: export interface ButtonProps { kind?: 'normal' | 'flat' | 'primary'; negative?: boolean; size?: 'small' | 'big'; spinner?: boolean; ...

Sign up for a feature that provides an observable exclusively within an if statement

There is an if clause in my code that checks for the presence of the cordova object in the window global object. If cordova is present, it will make a http request and return the default angular 2 http observable. If the application is in a web context wh ...

Stop Angular 2 from loading on Internet Explorer

I'm looking for a way to stop my Angular 2 application from loading on any version of Internet Explorer. I attempted using a script tag in index.html to detect IE, which was successful. However, when trying to redirect the app to a "not compatible pag ...

Challenges faced when integrating Angular with Bootstrap elements

I am currently in the process of developing a website using Angular 12, and although it may not be relevant, I am also incorporating SCSS into my project. One issue that I have encountered pertains to the bootstrap module, specifically with components such ...

What is preventing me from assigning to a class variable within a $http success handler?

During the course of my project, I have encountered a perplexing situation that is difficult to comprehend. My intuition tells me that the issue lies in a peculiar nuance of javascript while I am working in TypeScript. Unfortunately, I am unable to prove t ...

How to access data within nested objects using ngFor in Ionic 4

How can I access the data I need from an API when it is nested within multiple objects? I am attempting to retrieve the full_url from the data object, which is nested inside the avatar object. I have already attempted the following: <ion-list> ...

Displaying time in weekly view on the Angular 4.0 calendar

I've integrated the library into my Angular application to manage calendar events display and creation. The app features a monthly, weekly, and daily view option for users. However, I noticed that in the weekly view, only the dates are shown without ...

Tips on extending the response wait time for an API request using Observable RxJS in Angular

I have a Java Spring Boot backend application and an Angular frontend. In my front end, I am using a REST API to delete a file on the server but I keep getting a 404 error even though the service has been consumed and finished correctly. I suspect that th ...

Currently in motion post file selection

I am currently facing an issue with a button that triggers a file selector pop-up. Below is the code snippet: <button mat-raised-button (click)="inputFile.click()">Choose a file</button> <input #inputFile type="file" [style.display]="' ...

What could be the reason behind encountering the error stating "Type 'Number' does not have any compatible call signatures"?

Hey there, I am currently working on an angular component and I have this code snippet: private approvals: Approval[] = []; ngOnInit() { this.getUsersApprovals(this.userid); } getUsersApprovals(userid) { this.approvalsService.getUsersApp ...

What is the most efficient way to update data multiple times by mapping over an array of keys in a react hook?

My question might not be articulated correctly. I'm facing an issue with dynamically translating my webpage using Microsoft's Cognitive Services Translator. I created a react hook for the translator, which works well when I need to translate a si ...

Dealing with Angular package.json and unresolved peer dependencies

As I embark on the journey of developing an Angular project using CLI, I am also exploring additional components like angular handsontable and primeng. Amidst this exploration, a wave of confusion hit me when I attempted to check the versions of various pa ...