4

I want to deconstruct an object and exclude a property.

This is what I'm doing right now:

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

I found an article about ES7 which states there is a new feature to exclude properties. So the above would be written like this:

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

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

The above doesn't work in Angular 7 and I get the following error:

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

I'm currently running TypeScript 3.1.6, and my tsconfig.app.json file looks like this.

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

Here is the parent file.

{
  "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"
    ]
  }
}

Now I think the issue is that the line "lib": ["es2017"] is for ES6.

What can I do to enable this ES7 feature and will it break targeting ES5 as the compiled output from TypeScript?

2 Answers 2

12

Simply update your line - let y = {c, ...x}; with const {c, ...noC} = x;. So your code would be -

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

console.log(noC);

Suggestion: It's a good practice to make x constant, if you are not going to update it later.

Sign up to request clarification or add additional context in comments.

3 Comments

My holiday gift :)
For the sake of completeness, if the object's property is not a valid JavaScript identifier, e.g. 'x-http-header', just map it to a valid identifier. Example const {'x-http-header':omit, ...include} = headers.
Within a function the object key has to be wrapped in square brackets: const omit = <T, K extends keyof T>(obj:T, key:K): Omit<T,K> => {const {[key]:omit, ...keep} = obj; return keep}
7

Order sholud be like this

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.