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?