I have a baseMenu
object in which the dishes that are common across all the branches are present. I also have a city based menu chicagoMenu
and houstonMenu
that are specific to Chicago and Houston respectively.
Is it possible in typescript for one object to extend all the properties and their values of another object. In my case, can chicagoMenu
and houstonMenu
extend the properties of baseMenu
object.
The requirement is that when I iterate over the city based menu like chicagoMenu
, it should contain all the dishes of basemenu
and chicagoMenu
as well
let baseMenu = [
{dish : "fried chicken", price :"3$"},
{dish : "pepsi", price :"1$"},
{dish : "burger", price :"2$"},
]
let chicagoMenu = [
{dish : "pizza", price :"3$"},
{dish : "hot dog", price :"1#"}
]
let houstonMenu = [
{dish : "sandwich", price :"2$"},
{dish : "Orange juice", price :"2$"}
]
2
Answers
Yup you easily do it like this
The spread operator ‘…’ is used to include all the dishes from ‘baseMenu’ in the ‘chicagoMenu’ and ‘houstonMenu’.In this way, when you iterate over chicagoMenu or houstonMenu, they will contain all the dishes from baseMenu as well as their own specific dishes.
If you want to read more about this
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
You can refer to this link
I assume this is not just about Typescript but Javascript.
The Typescript part… You should set a type for base menu and since the others objects are the same type, I mean, they share the same properties, you can use this type as well.
As for the Javascript part, if you want to iterate over all objects, you should merge them into a single array.
The three dots before each object in the array means all their properties will be copied to the array.