Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typescript how to declare nested data type from interface

Tags:

typescript

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?

like image 697
Curzon Avatar asked Feb 23 '17 08:02

Curzon


People also ask

How would you define nested object type in TypeScript?

Typescript allows you to add a type for the object keys using the syntax [key: string] . As stated in the documentation, these are called indexable types: Indexable types have an index signature that describes the types we can use to index into the object, along with the corresponding return types when indexing.

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

One of which is Array of Objects, in TypeScript, the user can define an array of objects by placing brackets after the interface. It can be named interface or an inline interface.

How do you update a nested object in TypeScript?

To update nested properties in a state object in React: Pass a function to setState to get access to the current state object. Use the spread syntax (...) to create a shallow copy of the object and the nested properties. Override the properties you need to update.

What is Obj in TypeScript?

In TypeScript, object is the type of all non-primitive values (primitive values are undefined , null , booleans, numbers, bigints, strings). With this type, we can't access any properties of a value.


1 Answers

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
like image 176
basarat Avatar answered Nov 15 '22 05:11

basarat