【问题标题】:How to deconstruct an object and exclude a property?如何解构对象并排除属性?
【发布时间】:2019-05-20 02:02:38
【问题描述】:

我想解构一个对象并排除一个属性。

这就是我现在正在做的事情:

 let x = {a:1, b:2, c:3};
 let y = {...x};
 delete y.c;
 store.setState(y);

我发现一篇关于 ES7 的文章指出有一个新功能可以排除属性。所以上面会写成这样:

 let x = {a:1, b:2, c:3};
 store.setState({c, ...x});

https://codeburst.io/use-es2015-object-rest-operator-to-omit-properties-38a3ecffe90

上述方法在 Angular 7 中不起作用,我收到以下错误:

error TS2663: Cannot find name 'c'. Did you mean the instance member 'this.c'?

我目前正在运行 TypeScript 3.1.6,我的 tsconfig.app.json 文件看起来像这样。

{
    "extends": "../tsconfig.json",
    "compilerOptions": {
        "outDir": "../out-tsc/app",
        "module": "es2015",
        "types": []
    },
    "exclude": [
        "src/test.ts",
        "**/*.spec.ts"
    ]
}

这是父文件。

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "importHelpers": true,
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ]
  }
}

现在我认为问题在于"lib": ["es2017"] 是针对 ES6 的。

我可以做些什么来启用这个 ES7 功能,它会破坏将 ES5 作为 TypeScript 的编译输出吗?

【问题讨论】:

    标签: javascript angular typescript ecmascript-2016


    【解决方案1】:

    只需将您的行 - let y = {c, ...x}; 更新为 const {c, ...noC} = x;。所以你的代码是 -

    const x = {a:1, b:2, c:3};
    const {c, ...noC} = x;
    
    console.log(noC);

    建议:如果您以后不打算更新它,最好让x 保持不变。

    【讨论】:

    • 我的节日礼物 :)
    • 为了完整起见,如果对象的属性不是有效的 JavaScript 标识符,例如'x-http-header',只需将其映射到一个有效的标识符。示例const {'x-http-header':omit, ...include} = headers.
    • 在函数中,对象键必须用方括号括起来:const omit = <T, K extends keyof T>(obj:T, key:K): Omit<T,K> => {const {[key]:omit, ...keep} = obj; return keep}
    【解决方案2】:

    顺序应该是这样的

    let { c, ...y} = x;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-22
      • 2019-09-18
      • 1970-01-01
      • 1970-01-01
      • 2021-04-10
      • 1970-01-01
      • 2016-01-13
      • 2017-10-25
      相关资源
      最近更新 更多