0

I have an object which I use in multiple places in my React app:

   export default {
      'One': { Key: Foo.Bar, Color: '#eeeeaa' },
      'Two': { Key: Foo.Bar, Color: '#aaeeee' },
      'Three': { Key: Foo.Bar, Color: '#ffaaaa'},
    };

In a specific component I need this object but without the key 'Three'.

When I try:

import MyObjects from './';

const newObject = delete MyObjects.Three;

I get:

The operand of a 'delete' operator must be optional.ts

How to solve this issue or is there a cleaner approach?

Update:

When I try:

  const myObject2 = MyObjects;
  const { Three, ...testData } = myObject;
  console.log(testData);

Then I get Eslint error:

'Three' is assigned a value but never used.eslint@typescript-eslint/no-unused-vars

meez
  • 3,783
  • 5
  • 37
  • 91
  • 1
    Don't mutate the export of another module. The error has prevented you from making a mistake which would have caused a lot of trouble in the other components - good! Instead, create a *new object* that doesn't contain that key `Three` - see https://stackoverflow.com/questions/208105/remove-properties-from-objects-javascript – Bergi Dec 21 '21 at 17:48
  • @Bergi then I get `'Three' is assigned a value but never used.eslint@typescript-eslint/no-unused-vars`. I updated my question. Do you have an idea? – meez Dec 21 '21 at 17:57
  • Re your update: ignore the rule in that line or use `const { Three: _, ...testData } = myObject;`, which is usually allowed by that rule. See also https://stackoverflow.com/q/62839717/1048572 and https://stackoverflow.com/questions/56151661/omit-property-variable-when-using-object-destructuring and many more – Bergi Dec 21 '21 at 17:57
  • Not sure if you this would help.. const newObj = {'one': [MyObjects.One], 'two': [MyObjects.Two]} or Object.keys(MyObjects).forEach(key => { if (key !== 'Three') { obj[key] = MyObjects[key]; } }) – Dreamweaver Dec 21 '21 at 18:15

1 Answers1

-1

Reading this :

The operand of a 'delete' operator must be optional.

You need to use interfaces along with an optional key. Instead of directly exporting you can create a variable with type that specific interface.

? is used to indicate optional properties. They can be deleted (as your error indicates).

export interface Key {
 Key : string,
Color : string
}

export interface Colors {
     One : Key,
     Two : Key,
Three? : Key
}
const defaultColors : Colors = {
      'One': { Key: Foo.Bar, Color: '#eeeeaa' },
      'Two': { Key: Foo.Bar, Color: '#aaeeee' },
      'Three': { Key: Foo.Bar, Color: '#ffaaaa'},
    };
export default defaultColors;

One more way is to create an interface with just the two colors and then a second interface that extends the first (along with adding property Three).

Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39