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?

2 Answers 2

14

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.

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

2 Comments

So if the restaurants array could contain both IRestaurant and IHotel entries then only the first method would work, by having an Array<IRestaurant | IHotel> am I right?
I think that should work but I would use the new syntax and do [IRestaurant | IHotel][]
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.

1 Comment

This worked well for me.

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.