Dealing with Typescript types in a model when there is a possibility of multiple types

When it comes to the business logic of a model, there are different approaches depending on whether the entity should be expanded or just have IDs in the model. For instance:

class Order{
id:string;
product:Product
}
class Product{
id:string;
name:string;
price:number:
}

For the order response, the product can either be an expanded object or just the ID if complete data has not been requested. So how should one handle this in a TypeScript model? Is using a union on the order model considered good practice or should separate models be used?

Answer №1

The question is currently ambiguous.

  1. However, if the necessity for class features is absent, I would recommend utilizing TypeScript's interface instead. It offers type-checking without the overhead of a class structure.

  2. In addition, you have the option to declare properties as optional using ?:. This allows an object to conform to the interface type without the optional property.

interface Order {
  id: string;
  product?: Product;   // <-- `product` is optional
}

interface Product {
  id: string;
  name: string;
  price: number;
}

For Example

const order: Order = { id: 'sample', product: {...} };  // <-- works
const order2: Order = { id: 'sample' };  // <-- also works

Update: product could be of type Product or
string</h3>
<p>To address this situation, you can use union types to specify the type as either <code>Product
or string.

interface Order {
  id?: string;
  product?: Product | string;
}

Answer №2

To create the item as such:

item: string | Item;

I trust I have comprehended your inquiry correctly!

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

Firestore rules restrict access to the data, however the Angular project is still able to retrieve the collection - ERROR Error: Insufficient permissions or missing

I am currently working on an Angular project that is connected to a Firestore database. Within the database, there is a collection called users, and each document within this collection contains a nested collection named hugeCollection. I have updated the ...

Optimal Approach to Handling Errors in Angular's HttpClient

What is the most effective way to manage errors in HttpClient? Is this a viable approach? I want to avoid duplicating the same method multiple times in all services. export class HttpErrorHandler { static handleError(error: HttpErrorResponse) { le ...

Both buttons are calling the same function in Angular 6

I have created a component called add-customer.component.html <form [formGroup]="addCusForm"> <div id="login-container"> <h2 class="add-title">Customer Details</h2> <mat-form-field class="example-full-width ...

Find the sum of individual data points in chart.js by taking into consideration their respective

I created a line chart using the Chart.js library. My goal is to calculate the weighted sum when hovering over a specific data point, based on the difference between that point and its neighboring points. For instance, if point[0] = 5 with weight 2, point[ ...

What could be the reason for receiving the error message "NgModule' is not found" even after executing the command "npm i @types/node --global"?

Even though I tried following the suggestions provided in this Stack Overflow thread, I am still encountering the error "TypeScript error in Angular2 code: Cannot find name 'module'". My development environment consists of Angular 5 and npm versi ...

What is the process for sending a GET request with a URL-encoded object in Angular?

I am struggling with a complex object: { valueA:'a', value_array: { 'v': {value:1, value:2}, 'v2': {value:1, value:2}, } } Is there a way to encode it as a URL string for a GET request using Angular's HTTP servic ...

Encountered an issue while trying to access a property that is undefined in the

How can I extract data from a dropdown menu and display it in a text box? For instance, if a user selects an ID from the dropdown, I want to show the corresponding name in the textbox. I hope this explanation is clear and properly conveyed, as my English s ...

In order to maintain a custom tooltip in an open state until it is hovered over, while also controlling its

When hovering over the first column of the table, a tooltip will appear. Within each material tooltip, I would like to include a button at the bottom right after the JSON data. When this button is clicked, it should open an Angular Material dialog. <ng ...

Is there an error with the ngIf condition in the component's template?

I encountered an issue within the BlockComponent: The error message reads: "Can't bind to 'ngIf' since it isn't a known property of 'app-adresat-list'." In the template of the BlockComponent, you will find: <app-adresat- ...

Validation Form Controls

Here is a piece of code that works for me: this.BridgeForm = this.formBuilder.group({ gateway: ["", [Validators.required, Validators.pattern(this.ipRegex)]], }); However, I would like to provide more detail about the properties: this.BridgeF ...

Validation error from Express-validator may result in TypeScript error: the request.query object could potentially be undefined

Recently, as I was developing a Node.js app using express, I decided to enhance it with express-validator. Despite being new to express-validator, the warnings it generated perplexed me due to its lack of detailed documentation. To illustrate my point, he ...

Utilizing an onChange handler to dynamically update an array of objects with new data entries

My challenge involves manipulating an array of objects with JavaScript [ { "0": { "title": "Jessica Simpson", "id": "324352342323432", "url": "image-url.jpg", ...

Creating dynamic queries in Nodejs using MongoDB aggregation with both AND and OR conditions

I am facing an issue with MongoDB aggregation in my nodejs code. const query = { '$expr':{ '$and':[ {'$eq': ['$appId', req.user.appId]}, ] } } A filter object is coming from the frontend: { shops ...

The proxy request gets delayed unless I utilize the http-proxy-middleware

Here is the code for a provider: @Injectable() export class GameServerProxyService { private httpProxy: httpProxy; constructor(@Inject(GameServerDetailsService) private gameServiceDetailsService: GameServerDetailsService) { this.httpP ...

Avoiding circular imports in Angular modules

After restructuring my angular app from a monolithic shared feature module to smaller ones, I faced a challenge with what appears to be a cyclic dependency. The issue arises when I have components such as triggerA, modalA, triggerB, and modalB interacting ...

You cannot assign type 'Node | null' to type 'Node' when attempting to loop through HTML elements in TypeScript

In my code, I am taking a raw Markdown string stored in 'markdownString' and using the marked.js library to convert it to HTML for display on a web browser. My goal is to extract all plain text values from the page and store them in an array of s ...

Attempting to retrieve a URL using Angular/Typescript is generating an Unknown Error instead of the expected successful response

I'm trying to make a simple HTTP function call through TypeScript (Angular) to an API hosted as a function in Azure. When I call the URL through Postman or directly in the browser, everything works perfectly. However, when I try to call the URL usin ...

There was an error in calling `prisma.user.findUnique()`:

Here is my code snippet for the API route: export const POST = async (req: NextRequest) => { ... try { const { email, name, password } = await req.json(); console.info(email, name, password); const existingUser = await prismadb.user.findUn ...

Issue with TypeScript when using destructuring on an object

When attempting to destructure data from an object, I encountered the error message Property XXXX does not exist on type unknown. This issue arose while using React Router to retrieve data. let {decoded, reasonTypes, submissionDetails} = useRouteLoaderDa ...

Adding style tags dynamically to a component and then encapsulating the styles again (using Angular)

Currently, I am in the process of upgrading from AngularJS to Angular. Our app is currently a hybrid one being bundled up with webpack instead of just angular cli. Due to this setup, we have encountered issues where our css or scss files are not correctly ...