Tips for showcasing an array containing two different types of objects in Angular

After sending a request to a remote server, I am returned with a JSON array. However, the array can contain two different types of JSON objects:

[
  {
    "country": "USA",
    "caseCount": 561,
    "caseDates": [],
  },
  {
    "country": "Canada",
    "errorDescription": "Error"
  }
]

To handle this, I have created two interfaces and a variable that can hold either of these types:

export interface CountryData {
  country: string;
  caseCount: number;
  caseDates: any[];
}

export interface ErrorData {
  country: string;
  errorDescription: string;
}

countryData!: Observable<(CountryData| ErrorData)[]>;

When trying to display this data in my template with

*ngFor="let data of countryData | async"
, it only displays values common to both interfaces, such as the country field. I would like to modify this behavior to render values based on the type of the data object.

Answer №1

In order to handle different types of data in TypeScript, you need to utilize a concept known as type narrowing.

Here's an example:

interface UserData {
  username: string;
  age: number;
  email: string;
}

interface ErrorDetails {
  message: string;
}

userDataToString(data: UserData | ErrorDetails) {
  if (!data) {
    // When data is null or undefined
    return typeof data;
  } else if ('message' in data) {
    // If it's an error object
    return `ERROR: ${data.message}`;
  } else {
    // If it's user data
    return `${data.username} (${data.age} years old, email: ${data.email})`;
  }
}

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 process for including headers while establishing a connection to a websocket?

After configuring a websocket topic using Spring websocket on the server side, we implemented the client side with Stomp.js to subscribe to it. Everything was functioning correctly when connecting directly to the websocket service. However, we decided to i ...

The definition of "regeneratorRuntime" is missing in the rete.js library

After encountering a problem, I managed to find a potential solution. My current challenge involves trying to implement Rete.js in Next.js while using Typescript. The specific error message that's appearing is: regeneratorRuntime is not defined Be ...

Expanding a JSON type in Typescript to accommodate interfaces

Expanding on discussions about passing interfaces to functions expecting JSON types in Typescript, this question delves into the complexities surrounding JSON TypeScript type. The scenario involves a JSONValue type that encompasses various data types like ...

Setting up Emotion js in a React TypeScript project using Vite 4

Currently, I am in the process of transitioning from Webpack to Vite for my React Typescript application. I have been attempting to integrate Emotion js into the project. "@vitejs/plugin-react": "^4.0.1", "vite": "^4.3.9 ...

Steps to filter types by a singular property assessment

export type HalfSpin = { halfspin: string } export type FullSpin = { fullspin: string } export type SpinType = | HalfSpin | FullSpin export function isHalfSpin(_: SpinType) ...

Transformation of Ionic 2 ScreenOrientation Plugin

Can someone assist me with this issue? A while back, my Ionic 2 app was functioning correctly using the ScreenOrientation Cordova plugin and the following code: window.addEventListener('orientationchange', ()=>{ console.info('DEVICE OR ...

What is the proper way to validate a property name against its corresponding value?

Here is the structure of my User class: export class User { public id: number; //Basic information public email: string; public firstName: string; public lastName: string; //Permissions public canHangSocks: boolean; p ...

How to set the type of an object property to a string based on a string from an array of strings in TypeScript

Great { choices: ['Bob', 'Chris', 'Alice'], selectedChoice: 'Alice', } Not So Good { choices: ['Bob', 'Chris', 'Alice'], selectedChoice: 'Sam', } I've been exp ...

Is there a way to avoid waiting for both observables to arrive and utilize the data from just one observable within the switchmap function?

The code snippet provided below aims to immediately render the student list without waiting for the second observable. However, once the second observable is received, it should verify that the student is not enrolled in all courses before enabling the but ...

How can I receive live notifications for a document as soon as it is created?

My Angular app is connected to Cloud Firestore, and I've created a function in a service to retrieve a user's rating from the 'ratings' collection. Each rating is stored in this collection with the document ID being a combination of the ...

Issue encountered while utilizing property dependent on ViewChildren

Recently, I designed a custom component which houses a form under <address></address>. Meanwhile, there is a parent component that contains an array of these components: @ViewChildren(AddressComponent) addressComponents: QueryList<AddressCo ...

Can someone please explain how to display a specific element from a JSON Array?

Is there a way to display only this specific part? /db/User_DataDb/61500546-4e63-42fd-9d54-b92d0f7b9be1 from the entirety of this Object obj.sel_an: [ { "__zone_symbol__state":true, "__zone_symbol__value":"/db/User_DataDb/61500546-4 ...

The TypeScript compiler is unable to locate the identifier 'Symbol' during compilation

Upon attempting to compile a ts file, I encountered the following error: node_modules/@types/node/util.d.ts(121,88): error TS2304: Cannot find name 'Symbol'. After some research, I found that this issue could be related to incorrect target or l ...

Splitting code efficiently using TypeScript and Webpack

Exploring the potential of webpack's code splitting feature to create separate bundles for my TypeScript app has been a priority. After scouring the web for solutions, I stumbled upon a possible lead here: https://github.com/TypeStrong/ts-loader/blob/ ...

Guide on how to duplicate a form upon clicking an "add" link in Angular 2

Is it possible to dynamically repeat a form in Angular2 when clicking on a link? I am looking for a way to add the same form below the previous one when a specific link is clicked. Any suggestions or immediate replies would be greatly appreciated. For ins ...

Snackbar and RTK Query update trigger the error message: "Warning: Cannot update during an existing state transition."

I've built a basic ToDos application that communicates with a NodeJS backend using RTK Query to fetch data, update state, and store cache. Everything is functioning properly as expected with the communication between the frontend and backend. Recently ...

The object literal can only define properties that are already known, and 'data' is not found in the type 'PromiseLike<T>'

When making a request to a server with my method, the data returned can vary in shape based on the URL. Previously, I would cast the expected interface into the returned object like this: const data = Promise.resolve(makeSignedRequest(requestParamete ...

Sending information from the parent component to the child Bootstrap Modal in Angular 6

As a newcomer to Angular 6, I am facing challenges with passing data between components. I am trying to launch a child component bootstrap modal from the parent modal and need to pass a string parameter to the child modal component. Additionally, I want t ...

Guidelines on adjusting the hue of the card

I have created a directive to change the color of cards @Directive({ selector: "[appColor]", }) export class ColorDirective { @Input("color") color: string; constructor(private element: ElementRef, private render: Renderer2) { ...

Tips for establishing communication between a server-side and client-side component in Next.js

I am facing a challenge in creating an interactive component for language switching on my website and storing the selected language in cookies. The issue arises from the fact that Next.js does not support reactive hooks for server-side components, which ar ...