webstorm 开发 typescript 常见问题总结
ESLint中no-param-reassign错误
不改变原对象(数组)并重新给字段赋值,适用于ESLint4.0.0规则
Assignment to property of function parameter ‘item’
不能增加/删除对象属性
以上两个问题常用解决方法如下:
function defineProperty(obj, key, val) { // 返回object对象 return Object.defineProperty(obj, key, {value: val, writable: true, configurable: true, enumerable: true, } ); } function setObjectValue(obj, key, val){ return Reflect.set(obj, key, val);// 返回是否设置成功 } const tmp = {aa: "aa1", bb: "bb1", cc: "cc1"}; function handle(tmp) { // tmp.aa = "aa2"; // error: no-param-reassign defineProperty(tmp, "aa", "aa2"); // 方案3(适用于数组字段赋值) // tmp.bb = "bb2"; // error: no-param-reassign setObjectValue(tmp, "bb", "bb2"); // 方案2(适用于数组字段赋值) // tmp.cc = "cc2"; // error: no-param-reassign const tmpp = tmp; // 方案1 tmpp.cc = "cc2"; } handle(tmp); const arr = [tmp]; function handleArr(arr, index){ setObjectValue(arr[index], "aa", "aa3"); //defineProperty(arr[index], "aa", "aa3"); } handleArr(arr, 0); console.log(tmp); // {aa: "aa2", bb: "bb2", cc: "cc2"} console.log(arr);