简体   繁体   中英

How to perform a destructuring assignment of a javascript object to already declared variables inside the scope of a class

I need your help, because I am trying to get a destructuring assignment of a javascript object inside of variables already declared inside the scope of a class... ie , I need to use {this.property, ... }

({ this.baseINSS,
  this.baseIRPF,
  this.discountINSS,
  this.dependentesDiscount,
  this.discountIRPF,
  this.netSalary } = calculateSalaryFrom(element.target.value, Number(dependentes)));

The above mentioned function calculateSalaryFrom() will return

{baseINSS: "9876",
baseIRPF: 9162.9,
dependentesDiscount: 0,
discountINSS: 713.1,
discountIRPF: 1650.44,
netSalary: 7512.459999999999,
percentageDependentes: "0.00",
percentageINSS: "7.22",
percentageIRPF: "16.71",
percentageSalary: "76.07"}

I am geting the error TS1005: ':' expected.({ this.baseINSS,... By the way, I am using angular and typescript

Object destructuring without colons can only be done into works for valid standalone identifiers. Eg

({ this.baseINSS } = someObj);

won't work because the property of someObj isn't this.baseINSS - it's just baseINSS .

While you could rename the property as you destructure:

({ baseINSS: this.baseINSS, discountINSS: this.discountINSS } = calculateSalaryFrom(...

That'll get repetitive.

Destructuring won't work well here. Iterate over an array of property names instead.

const obj = calculateSalaryFrom(element.target.value, Number(dependentes)));
const props = ['baseINSS', 'baseIRPH', ...] as const;
for (const prop of props) {
  this[prop] = obj[prop];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM