Home > Mobile >  How to delete all keys from an object in typescript
How to delete all keys from an object in typescript

Time:04-01

I am trying to access the keys in an object which is of type FilterType

Here is the interface -

export interface FilterType {
  name?: string[];
  status?: string[];
  brand?: string[];
  categoryAndColour?: {
    [category: string]: string[];
  };
  rating?: string[];
}

Here is the object -

const newState: FilterType = { ...state };

I am trying to have a function which will remove all the keys from newState however whenever I try to map through the object or to a for..in I keep getting similar errors.

I am currently trying this -

for (var key in newState){
        delete newState[key];
      }
      return newState;

But I get the error Element implicitly has an 'any' type because expression of type 'string' can't be used to index type

And No index signature with a parameter of type 'string' was found on type

How can I solve this?

CodePudding user response:

Since you're trying to create a new empty state, just define the newState as a new object:

const newState: FilterType = {};

If you still want to delete all the keys anyway, define the type of key before using it in for..in (TS playground):

let key: keyof FilterType;

for (key in newState){
  delete newState[key];
}

CodePudding user response:

Why don't you just return an empty object to this state?

CodePudding user response:

Try this:

Object.keys(newState).forEach((key) => delete newState[key]);

now, if you run:

console.log(newState)

the expected output will be an empty object:

{ }
  • Related