J
J
JavaSscriptNoob2021-12-11 18:40:25
typescript
JavaSscriptNoob, 2021-12-11 18:40:25

Why is the error Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'EventStatusType'. in ts?

my type

export type EventStatusType = {
  Open: boolean;
  Closed: boolean;
  Maintaince: boolean;
};

object
EventTypes: {
Closed: false,
Maintenance: false,
Open: false
}

The code that causes the error
for (let key in eventTypes) {
    if (eventTypes[key]) { // ТУТ ОШИБКА eventTypes[key]) - булевое значение
      switch (key) {
        case 'Open':
          url = isFirst ? url.where('slss.EndDate', EMPTY, '') : url.or('slss.EndDate', EMPTY);
          isFirst = false;
          break;
        case 'Closed':
          url = isFirst
            ? url.where('slss.EndDate', GREATER_THAN, startDate.toISOString())
            : url.or('slss.EndDate', GREATER_THAN, startDate.toISOString());
          isFirst = false;
          break;
        case 'Maintenance':
          url = isFirst
            ? url.where('slss.EventType', EQUAL, 'Maintenance')
            : url.or('slss.EventType', EQUAL, 'Maintenance');
          break;
      }
    }
  }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aetae, 2021-12-12
@Aetae

let key: keyof EventStatusType;
for (key in eventTypes) {
Typescript can't automatically infer the type keybecause it's a struct , and there's no way it can know that there are definitely no other keys in an object other than those specified in the type EventStatusType:
const foo = {
   Closed: false,
   Maintaince: false,
   Open: false,
   внезапно: 'Вася'
};

const bar: EventStatusType = foo; // ok
Since with the help of the code at the beginning you are actually telling Typescript: “I know better, there definitely won’t be anything else”, then just in case of an emergency, you should add switch defaultsomething to it (for example, throw an error) if an extra unknown key arrives.
P.S. And you also have a typo in the name of one key: Maintainceand Maintenance.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question