J
J
Julia2021-09-03 17:40:53
typescript
Julia, 2021-09-03 17:40:53

How to iterate an object that inherits from an interface?

I have a tasks object that inherits from the ITaskListState interface. I need to go through all the fields of an object and filter them by condition.
tasks:

tasks: ITaskListState = {
    tasksToDo: new Array<ITaskItem>(),
    tasksInProgress: new Array<ITaskItem>(),
    finishedTasks: new Array<ITaskItem>(),
  }

InterfaceITaskListState:
export interface ITaskListState
{
  tasksToDo:  Array<ITaskItem>,
  tasksInProgress: Array<ITaskItem>,
  finishedTasks:  Array<ITaskItem>,
}

I tried to implement filtering like this:
filterTasks(filteredTask: ITaskItem)
  {
    for (let key in this.tasks)
    {
      this.tasks[key] = this.tasks[key].filter((task: ITaskItem) => task !== filteredTask);
      console.log(key);
    }
}

But at compile time I get the error:
TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'ITaskListState'. No index signature with a parameter of type 'string' was found on type 'ITaskListState'.

How can I get around this compiler error?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexandroppolus, 2021-09-03
@JuliaClifford

filterTasks(filteredTask: ITaskItem) {
  const keys = Object.keys(this.tasks) as Array<keyof ITaskListState>;

  for (let i = 0; i < keys.length; ++i) {
    const key = keys[i];
    this.tasks[key] = this.tasks[key].filter((task: ITaskItem) => task !== filteredTask);
    console.log(key);
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question