Curzon
Curzon

Reputation: 113

typescript how to declare nested data type from interface

I have the following typescript interface:

interface IFoodShop {
    name: string;
    owner: string;
    foods: Array<{
        id: number,
        name: string,
        isVegetarian: boolean
    }>
}

I have a function that requires the paramater to be the same data type as the foods array from interface IFoodShop. How would i declare it, similar to something this, which doesn't work.

// check if food is vegetarian
isVegatarianFood(data: IFoodShop.foods) {


}

I understand I can break down the data types like below:

interface IFoodShopFood {
    id: number,
    name: string,
    isVegetarian: boolean
}

interface IFoodShop {
    name: string;
    owner: string;
    openDate: Date;
    foods: IFoodShopFood
}

// check if food is vegetarian
isVegatarianFood(data: IFoodShopFood) {


}

But this to me seems unecessary when I have a lot of arrays to declare. How would I simply say that the data type needs to match the nested interface data type foods?

Upvotes: 5

Views: 13245

Answers (1)

basarat
basarat

Reputation: 275847

But this to me seems unecessary when I have a lot of arrays to declare.

You can use the following syntax (its called a lookup type):

interface IFoodShop {
    name: string;
    owner: string;
    foods: Array<{
        id: number,
        name: string,
        isVegetarian: boolean
    }>
}
// check if food is vegetarian
function isVegatarianFood(data: IFoodShop['foods']) { }

isVegatarianFood([{ id: 123, name: '123', isVegetarian: true }]); // okay
isVegatarianFood([{ id: 123, name: '123', isVegetarian: 'ERRROR' }]); // ERROR

Upvotes: 11

Related Questions