0

The structure of JSON that is received from the server is something like this(I changed details):

{
  "apple": {
    "fruitName": "apple",
    "types": {
      "greenApple": {
        "productCode": "P1",
        "productName": "Green Apple",
        "color": "green",
      },
      "galaApple": {
        "productCode": "P2",
        "productName": "Gala Apple",
        "color": "light red",
      },
      "redDelicious": {
        "productCode": "P3",
        "productName": "Red delicious apple",
        "color": "bright red",
      }
    }
  },
  "orange": {
    "fruitName": "orange",
    "types": {
      "mandarin": {
        "productCode": "P5",
        "productName": "Mandarin Oranges",
        "color": "orange",
      },
      "bloodOrange": {
        "productCode": "P6",
        "productName": "Blood Orange",
        "color": "red",
      }
    }
  },
}

I am coming up with an Interface structure using Typescript for my project.

So far I have come up with this:

export type FruitTypes = {
  [key: string]: Product,
}

export type Product = {
  productCode: string
  productName: string
  color: string
}

export type Fruits = {
  fruitName: string
  type: object<FruitTypes>
}

What I am not understanding is how to make a declaration in Fruits for type? type: object<FruitTypes> is not working. It is going to be an object of objects. How do we describe this in Typescript.

3
  • 1
    Would it not just be type: FruitTypes? Commented Jul 9, 2020 at 22:35
  • @Taplar Its an object of objects. i am not sure if it would work. Commented Jul 9, 2020 at 22:37
  • Lots of things are objects of objects. That's what most objects are. Things with key value pairs, some of which have values that are objects. I'm not sure I understand the issue. Commented Jul 9, 2020 at 22:39

1 Answer 1

5

I prefer to use Record<K,T>

export type Fruits = Record<string, FruitTypes>;

export type FruitTypes = {
  fruitName: string;
  types: Record<string, Product>;
}

export type Product = {
  productCode: string;
  productName: string;
  color: string;
}

or you can write it explicit

export type Fruits = {
  [key:string]: FruitTypes;
}

export type FruitTypes = {
  fruitName: string;
  types: {
    [key:string]: Product;
  };
}

export type Product = {
  productCode: string;
  productName: string;
  color: string;
}

Where Fruits is the type for the whole construct.

Sign up to request clarification or add additional context in comments.

1 Comment

This is exactly what I was looking for. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.