Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'SearchQuery'

Viewed 91

I have update tslint to eslint, and now for this class i have error like this

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'SearchQuery'.

This is class I am talking about

export abstract class SearchQuery {
    transformQueryIntoText(): QueryValue[] {
        const queryValues: QueryValue[] = [];
        for (const key of Object.keys(this)) {
            if (this[key]) {
                queryValues.push({
                    name: key,
                    value: this[key].toString()
                });
            }
        }
        return queryValues;
    }
}

I dont know even how to start?

1 Answers

Don't know if this will affect the intended usage of your SearchQuery class, but one approach could be to "tell" TSC that your base class will have dynamic properties. Something like this:

interface QueryValue {
  value: string;
  name: string;
}

export abstract class SearchQuery {
  [key: string]: unknown; // <-- This line
  transformQueryIntoText(): QueryValue[] {
    const queryValues: QueryValue[] = [];
    for (const key of Object.keys(this)) {
      if (this[key]) {
        queryValues.push({
          name: key,
          value: this[key].toString()
        });
      }
    }
    return queryValues;
  }
}

Now should be safe to call this[key]

Related