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'
};
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?
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!
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With