Complete only the fields specified in the Interface definition

I have been developing a shopping cart service that implements a method to add a specified JSON object to a cart object. However, only the defined fields in the IProduct interface should be populated.

JSON Object

{
    "title": "Title 1",
    "descriptionHtml": "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore.",
    "vendor": "1",
    "variants": [
        {
            "id": "aaaa",
            "price": "12.95",
            "quantity": "1"
        }
    ],
    "images": [
        {
            "transformedSrc": "https://path/to/image"
        }
    ],
    "filters": [
        "Pizza"
    ],
    "ratings": "1321"
}
import { Injectable } from '@angular/core';

export interface IProduct {
    title: string;
    descriptionHtml: string;
    vendor: string;
    variants?: (VariantsEntity)[] | null;
    images?: (ImagesEntity)[] | null;
}

export interface VariantsEntity {
    id: string;
    price: string;
    quantity: string;
}

export interface ImagesEntity {
    transformedSrc: string;
}

@Injectable({
    providedIn: 'root'
})

export class CartService
{
    cart: IProduct[] = [];

    constructor() { }

    setProduct(product)
    {
        this.cart.push(product);
    }
}

When using this.cart.push(product), it adds the entire JSON object. However, I am not interested in including fields like "filters" and "ratings".

Is there a way with Typescript to ensure that only the specified interface fields are included?

UPDATE: What solutions are available in this scenario?

Answer №1

Is it possible to generate only the specific interface fields in Typescript?

If you're seeking this functionality, you may be interested in utilizing "Exact Types". Unfortunately, they are not currently supported out of the box.

Additional Resources

Answer №2

Discovered a effective fix using the Spread Operator.

const {stats, conditions, ...filteredItem} = item;
this.inventory.push(filteredItem);

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

Switch the ngClass on the appropriate ancestor element for the dropdown menu

Utilizing Angular CLI version 8.3.0, I aim to construct a sidebar featuring a drop-down menu. My objective is to apply the "open" class to toggle the opening of the drop-down section. However, the current challenge I am encountering is that when I click to ...

What is the best way to invoke a method within the onSubmit function in Vuejs?

I am facing an issue with a button used to log in the user via onSubmit function when a form is filled out. I also need to call another method that will retrieve additional data about the user, such as privileges. However, I have been unsuccessful in makin ...

Having trouble with the yAxis in HighCharts on Angular 8? FireFox and IE causing issues?

Hey there! Currently, I am using "highcharts 8.0.0" along with "highcharts-angular 2.4.0" in combination with Angular 8. While the line charts are displaying perfectly fine on Google Chrome, I seem to be facing an issue with Firefox. The problem is that t ...

Angular: Automatically navigate to the parent page if the child parameter ID is missing

I currently have two separate modules with their own unique routing setups: CarsModule PassengersModule (Lazy Loaded) Passenger is essentially a child of car and can be accessed through the following URL structure: https://localhost/cars/12/passengers/1 ...

Error: ionic serve is unable to locate the 'reflect-metadata' module

I am new to Ionic2 and following the steps: $ npm install -g ionic cordova $ ionic start cutePuppyPics --v2 $ cd cutePuppyPics $ ionic serve However, I encountered an error: "Cannot find module 'reflect-metadata' $ ionic info Cordova CLI: 6.5 ...

Hold off on moving to the following page

My Angular website is performing well, but I've noticed that when clicking into a project, it loads the page instantly and there can be a flicker as the images are retrieved from the API. It would be ideal to have a slight delay or some sort of page t ...

Configuring .NET Core to send authentication cookies to a separate domain

I am facing an issue with using cookies on the frontend, which has a domain different from the backend. The backend is built with .Net Core and the frontend with Angular. I have learned that I need to set withCredentials: true when making http calls. Howev ...

Ways to implement a personalized JSON converter for a particular .NET Framework type

Currently, I am utilizing the JSON.NET library. I am interested in developing a personalized JsonConverter that can effectively transform a Dataset object into JSON format. Although I have created the Converter, I am uncertain of how to instruct the JSON. ...

"Encountered a problem while trying to insert data using JSON and Ajax

I've been struggling to figure out where the issue lies in my code. I've double-checked everything and it all seems correct, but I keep encountering errors. Below is the code snippet: Markup: <link href="http://ajax.googleapis.com/ajax/libs ...

What is the syntax for typing a mongoose populated field in Typescript?

I am faced with a field that can either be an ID or have a value, and I am attempting to type this field using TypeScript import { InferSchemaType, Schema, Types, model } from 'mongoose'; const personSchema = new Schema({ _id: Schema.Types.Obj ...

Is there a way to ensure that only individual objects are selected in FabricJS on the Canvas, rather than a group of objects?

One issue I am facing is with my method for selecting objects on the canvas by clicking a button. How do I ensure that it skips selecting groups and only selects individual objects? Generating a group of shapes here: const group = new fabric.Group([ ...

Leverage third-party extensions instead of ionic-native plugins in your Ionic 2

Currently, I am utilizing a Cordova plugin from GitHub that is not accessible in Ionic Native. However, I have encountered an issue. How can I effectively use non-Ionic-Native plugins in Ionic 2? I attempted the following: declare var myPlugin: any; my ...

Error: Jersey was unable to find the MessageBodyWriter for the list of XmlRootElement/Entities

Among the countless JAX-RS serialization examples out there, here's another one to add to the mix. Let's start with a JPA/JAXB annotated class: @Entity @XmlRootElement public class Foo implements Serializable { //.. } Now, imagine we have a se ...

Utilizing JSON to transfer PHP array data for display using JQuery

Currently, I am working on a jQuery script that is responsible for fetching a PHP array from the MySQL database and converting it into a JSON object. The process is functioning correctly, as I can successfully output the raw JSON data along with the keys. ...

having difficulty with installing the bootstrap framework

I'm having issues installing the ng-bootstrap in my project. I keep encountering the following error message. Despite trying to execute the commands below, I haven't had any success. npm install --legacy-peer-deps npm install latest-version He ...

Can you explain the meaning behind the exclamation mark in Angular syntax?

I've noticed this popping up in a few spots lately, but I haven't been able to find any information about it. I'm intrigued by the use of the '!' symbol in Angular syntax. Can anyone explain what it does? https://i.sstatic.net/sj ...

Generate custom fixtures using manager methods, implement JSON dumps, and prevent type errors using error handling techniques to ensure that :xxx is properly serialized in JSON

After considering various options, I decided to create a test fixture using custom manager methods due to my app's unique requirements. I opted out of using initial_data and instead implemented the following in Managers.py: Planetsdict = Planet.objec ...

Changing the behavior of the Json helper method in a base controller

I have a query that needs to be answered: In your application, AJAX requests will be handled by providing responses in JSON format. To have better control over serialization, you decide to create a customized ActionResult class. The aim is to override th ...

Implementing Angular Universal on Azure Platform

After converting my application to Angular Universal at the request of my clients, I successfully ran it using npm run serve:ssr and accessed it through http://localhost:4000. Now, the challenge lies in deploying it. Upon running npm run build:ssr, a dist ...

There seems to be a bug in the reducer within the store (using react, redux toolkit, and TypeScript)

Utilizing redux with typescript, I aim to create a reducer that will modify the state of the store, and my defined types are as follows: interface IArticle { id: number, title: string, body: string, } type ArticleState = { articles: IArticle[] } ...