Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a named array of objects in an interface with TypeScript?

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?

like image 710
Yohanna Avatar asked Mar 24 '17 07:03

Yohanna


People also ask

How do you define an array of objects in interface TypeScript?

To declare an array of objects in TypeScript, set the type of the variable to {}[] , e.g. const arr: { name: string; age: number }[] = [] . Once the type is set, the array can only contain objects that conform to the specified type, otherwise the type checker throws an error. Copied!

How do you declare an array in TypeScript?

Arrays can be declared and initialized separately. let fruits: Array<string>; fruits = ['Apple', 'Orange', 'Banana']; let ids: Array<number>; ids = [23, 34, 100, 124, 44]; An array in TypeScript can contain elements of different data types using a generic array type syntax, as shown below.

How do you define object of objects type in TypeScript?

To define an object of objects type in TypeScript, we can use index signatures with the type set to the type for the value object. const data: { [name: string]: DataModel } = { //... }; to create a data variable of type { [name: string]: DataModel } where DataModel is an object type.


1 Answers

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.

like image 102
codeBelt Avatar answered Oct 14 '22 15:10

codeBelt