Issue
I have an object that is going to have field products
, this field will be filled with the response returned by different endpoints which each return a type of product. something like:
const products = {
// each of this kind of products comes from endpoint response
someProduct: {},
someOtherProduct: {}
anotherProduct: {}
}
All product types share some common properties such as name, description, price. but they also have specific properties that apply only to one type of product. in some cases, I need to traverse all products to render a list of those common properties, but other times I need to render specific data for each type of product.
How do I type this product
object, if it contains different product types, each of which has different properties and comes from an external data source(server)?
EDIT 1: Product Type
Each product has an attribute type
, to identify each product type
EDIT 2: Selected product type
When I render all products in a list, the user can click on any of them and I store the selected product in a variable... so I can use that selected product to print specific product details... how to type this selected product, if it can be of any type of product?
Solution
UPDATED
You can also check one Working Example in CodeSandbox: With an Array and Selected Product, and all the styles: https://codesandbox.io/s/condescending-sea-53xh8?file=/src/App.tsx
ORIGINAL
You can do something like:
In this case, we are defining a BaseProduct for all the common attributes. We extend this product interface to define each of the other interfaces.
Then, we define a type Product
which can be any kind of the Product
interfaces defined previously.
And finally, we can define an Array of Product
(if your server answer with an array) or an object which can have any string as key
and Product
as values.
interface BaseProduct {
name: string;
description: string;
price: number;
type: string;
}
interface SomeProduct extends BaseProduct {
genericAttrOne: string;
genericAttrTwo: string;
}
interface OtherProduct extends BaseProduct {
anAttributeOne: string;
anAttributeTwo: string;
}
interface AnotherProduct extends BaseProduct {
anotherAttributeOne: string;
anotherAttributeTwo: string;
}
type Product = SomeProduct | OtherProduct | AnotherProduct;
const productsAsArray: Product[] = [];
const productsAsObject: { [key: string]: Product }: {};
Answered By - joseglego
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.