I’m currently building an ecommerce application for my company. And as the title, I’m facing a problem like this:
Usually, my product types from the API call would be something like:
content: [
isAvailable: boolean;
isSoldOut: boolean;
product: {
id: string;
productName: string;
}
seller: string;
]
But in a minor of cases, the actual response would be like:
content: {
id: string;
productName: string;
...
} []
basically only the body of the product, no extra information like the above
So in short, I just want to modify the response of the API (the minor-case one or the other way around) without having to touch the already-defined product.type.ts.
I did add an extra interface for this, but it made the app very complicated since I was trying to pass the data conditionally to any of the children components that use that data. Any help would be appreciated. Thanks!
2
Answers
This is not something you can do with a TypeScript interface/type as TypeScript doesn’t do anything at runtime. TypeScript offers static type checking which helps during development. But if you wish to alter the response body if it doesn’t match the desired format you would have to add some logic to your code that changes the properties present in the body.
i would suggest to create typeguard to check which data came and then work with these types (modify that not common one to common one or count with both types in every component)