8

How do I define the restaurants property in an interface with TypeScript?

let test = {
  user_id: 5,
  restaurants: [
    {
      restaurant_id: 5,
      restaurant_rank: 5
    },
    {
      restaurant_id: 6,
      restaurant_rank: 6
    }
  ],
  timestamp: 'test'
};

Note

I've looked at the following questions but none of them solved my problem:

How can I define an interface for an array of objects with Typescript?

How can I define an array of objects in typescript?

Community
  • 1
  • 1
Yohanna
  • 483
  • 1
  • 6
  • 14

2 Answers2

13

The way I would write is like this:

interface IRestaurant {
    restaurant_id: number;
    restaurant_rank: number;
    restaurant_details?: any;
}

interface IThing {
    user_id: number;
    timestamp: string;
    restaurants: Array<IRestaurant>;
}

const test: IThing = {
    user_id: 5,
    restaurants: [
        {
            restaurant_id: 5,
            restaurant_rank: 5
        },
        {
            restaurant_id: 6,
            restaurant_rank: 6
        }
    ],
    timestamp: 'test'
};

There is a few other ways you can do the array:

interface IThing {
    user_id: number;
    timestamp: string;
    restaurants: IRestaurant[];
}

interface IThing {
    user_id: number;
    timestamp: string;
    restaurants: Array<{restaurant_id: number, restaurant_rank: number}>;
}

I noticed in your replied answer you do restaurant_details: Object. You should do restaurant_details: any because Object is more restrictive than any. See https://stackoverflow.com/a/18961904/2592233

I also add a question mark after restaurant_details to tell the compiler this is optional since you didn't have in the first example.

Community
  • 1
  • 1
codeBelt
  • 1,727
  • 16
  • 22
  • So if the `restaurants` array could contain both `IRestaurant` and `IHotel` entries then only the first method would work, by having an `Array` am I right? – Arnold Schrijver Jun 15 '20 at 08:04
  • 1
    I think that should work but I would use the new syntax and do `[IRestaurant | IHotel][]` – codeBelt Jun 15 '20 at 22:05
2

Looking at this and this answers, I came up with the following:

 interface InterfaceName {
  user_id: number,
  restaurants: { [index: number]: { restaurant_details: Object, restaurant_rank: number } },
  timestamp: Date
}

However, I found out that it doesn't get detected as an array, so a simpler solution would be:

interface InterfaceName {
  user_id: number,
  restaurants: { restaurant_details: Object, restaurant_rank: number }[],
  timestamp: Date
}

Doing so will allow InterfaceName.restaurants to be correctly treated as array by the TypeScript compiler.

Community
  • 1
  • 1
Yohanna
  • 483
  • 1
  • 6
  • 14