- Mastering TypeScript 3
- Nathan Rozentals
- 192字
- 2021-07-02 12:42:48
Spread precedence
When using object spread, properties will be copied incrementally. In other words, if two objects both have a property with the same name, then the object property that was specified last will take precedence. As an example of this, consider the following code:
let objPrec1 = { id: 1, name: "object prec 1" }; let objPrec2 = { id: 1001, description: "object prec 2 descripton" } let obj4 = { ...objPrec1, ...objPrec2 }; console.log(`obj4 : ${JSON.stringify(obj4)}`);
Here, we have defined two objects named objPrec1 and objPrec2. Note that both have an id property, but objPrec1 has a name property, and objPrec2 has a description property. As we have already seen, the rest and spread syntax will combine the properties of both objects, but what does it do with the id property? Should it be 1 or 1001? The rest and spread syntax will use the last defined property value. This can be seen by running this code, and checking the obj4 object, as follows:
obj4 : {"id":1001,"name":"object prec 1","description":"object prec 2 descripton"}
Here, we can see that obj4 has taken the value of 1001 for the id property, as expected.