skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. 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)

    
    const isMajorType(data: Major | Minor): data is Major {
    return "isAvailable" in data
    }
    
    const transformData = (data: Major | Minor): Major =>{
    if(isMajorType(data)){
    return data
    }
    return // some transform magic
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search