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?
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.
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.
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.
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.
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
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