Retrieve the attribute from a TypeScript union data type

Here is the structure that I am working with:

export interface VendorState extends PaginationViewModel {
  vendors: CategoryVendorCommand[] | CategoryVendorCommand;
}

This is my model:

export interface CategoryVendorCommand {
    id: string;
    name: string;
    description: string;
}

I am attempting to access this property:

 this.patchValue({ name: item.vendors.name, description: item.vendors.description })

However, I am encountering an exception stating

Property 'name' and 'description' does not exist on type 'CategoryVendorCommand | CategoryVendorCommand[]'

Answer №1

Here is an example:

const _self = this;
const updateValue = (seller: CategorySellerCommand) => {
    _self.updateValue({ name: seller.name, description: seller.description });
});

// Example scenario (not tested)

if(Array.isArray(product.sellers)){
    product.sellers.forEach((seller) => updateValue(seller));
}
else {
    updateValue(product.sellers);
}

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 could be causing the Angular 5 error: "Cannot find exported module 'OpaqueToken'."?

I am currently in the process of upgrading my Angular 4 application to Angular 5. During this upgrade, I encountered the following error message: ERROR in src/app/application/services/generated/variables.ts(1,10): error TS2305: Module '"..../no ...

What is the best way to define a model class within my Angular 2 component using TypeScript?

As I delve into Angular 2 and TypeScript, I am keen on adopting best practices. I have decided to move away from a simple JavaScript model ({ }) in favor of creating a TypeScript class. However, it seems that Angular 2 is not very fond of my approach. T ...

Defining Array Types in TypeScript JSON

My attempt at coding a class in TypeScript has hit a roadblock. Whenever I try to utilize Jsons in an Array, the system crashes due to a TypeScript error. Here's the class I tried to create: class Api { url: string | undefined; credentials: Ar ...

Tips for configuring the Index column within an Angular Mat-table (when the dataIndex displays 'NaN')

My Mat-Table is working perfectly, but I am looking for a way to add an auto-increment index. Below is the HTML code: <div class="mat-elevation-z8"> <table mat-table [dataSource]="dataSource" matSort> <ng-container matColumnDef="no"> ...

In the realm of JavaScript and TypeScript, the task at hand is to locate '*' , '**' and '`' within a string and substitute them with <strong></strong> and <code></code>

As part of our string processing task, we are looking to apply formatting to text enclosed within '*' and '**' with <strong></strong>, and text surrounded by backticks with <code> </code>. I've implemented a ...

A single network request is made for every subscription

When making a post request using HTTPClient and subscribing to the returned observable, I am encountering strange behavior where each subscription triggers a new post request. So, if I subscribe to the observable 5 times, I end up with 5 separate post requ ...

Encountering errors while attempting to utilize Ionic plugins within a nxtend/ionic-angular project

I've been trying to integrate nxtend/ionic-angular into my project, but I encountered issues with using plugins. Here are the two use cases where I faced problems: 1st Use Case: I needed to retrieve the current application version, so I installed the ...

Inheritance of Type Member in TypeScript

My data structure looks like this: export abstract class Person { ... } export class FPerson extends Person { a: A; b: B; } export class JPerson extends Person { c: C; } export class User { person: Person; } When dealing with the s ...

Simultaneous asynchronous access to a single object

I have been working with JS/TS for quite some time now, but the concept of race conditions still perplexes me. I am currently attempting to execute the following logic: class Deployer { protected txDataList: Array<TXData>; constructor() { this ...

Activate backdrop feature in offcanvas mode

When trying to open an offcanvas panel, I discovered that adding show to its class is necessary for it to open. However, this caused the backdrop feature to stop working, and now clicking outside the panel does not close it. Is there a way to achieve the p ...

Adding two headers to a post request in Angular 2 - a step-by-step guide!

Is there a way to combine 2 headers in the following code snippet: appendHeaders(json: PortfolioVO) { var newJson = JSON.stringify(json); var allHeaders = new Headers(); allHeaders.append('Content-type' , 'application/jso ...

Error: Module './App' not found in webpack module

I am encountering the error Uncaught Error: Module not found: Can't resolve ./App' and ./store in client/src. in the console of my local environment when I execute npm start from the client directory. The console is showing 2 errors: ERROR in ...

trpc - Invoking a route from within its own code

After reviewing the information on this page, it appears that you can invoke another route on the server side by utilizing the const caller = route.createCaller({}) method. However, if the route is nested within itself, is it feasible to achieve this by ...

Exploring methods to successfully upload a blob to Firebase and modify it using cloud functions

For days now, I've been attempting to successfully upload a file to firestorage using firebase functions but haven't had any luck. This is the progress I've made so far: export const tester = functions.https.onRequest(async (request, respons ...

Check the validity of a password using Angular's reactive forms

For my password validation using ng Reactive Forms, I have a basic html input field for the password and warning paragraphs outlining the password requirements. <div class="field"> <label class="label">Password</label ...

Display a loading screen while transitioning between routes in Angular 2

Is there a way to implement a loading screen for route changes in Angular 2? ...

Combining Files in Angular 2 for Optimal Production Deployment

What is the best method for packaging and combining an Angular 2 application for production? My goal is to have an index.html file and a single app.min.js file. Although the Angular 2 documentation mentions using webpack, I found it to be overly complex f ...

The property is accessed prior to being initialized

In my code, I have a class defined as follows : export class Group { id: string; name: string = ''; type: 'local' | 'ldap' = 'local'; members: number[] = []; This class is being used in my applicatio ...

Wait until a svelte store value is set to true before fetching data (TypeScript)

I have implemented a pop-up prompt that requests the user's year group. Since I have databases for each year group, I need to trigger a function once the value of userInfo changes to true. My JavaScript skills are limited, and my experience has been ...

What could be causing my sinon test to time out instead of throwing an error?

Here is the code snippet being tested: function timeout(): Promise<NodeJS.Timeout> { return new Promise(resolve => setTimeout(resolve, 0)); } async function router(publish: Publish): Promise<void> => { await timeout(); publish(&ap ...