1
votes

I have an interface FilterData, which looks like the following:

export interface FilterData {
  variables?: string[];
  processDefinitionKey?: string;
}

In a request to the server, I receive the object filterSettings which is of a type FilterData, and I need to iterate over it.

This is what I'm doing right now:

for (const key in filterSettings) {
  filterString += `${key}_eq_${filterSettings[key]},`;
}

But I receive the following error:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'FilterData'. No index signature with a parameter of type 'string' was found on type 'FilterData'.ts(7053)

I read here that the interface doesn't exist on the runtime, but I have no idea about what workaround could be. How I can iterate over the interface object?

3
Can you please share your entire code? I don't think there's any problem with the code you posted here. const key in filterSettings, at runtime, does not use FilterData but just the object properties of filterSettings. It should work (and does in my little scratch file).fjc
i tried.. i didnt get error. did u try to update typescript ?xdeepakv
@xdeepakv You do get that error if your typescript config does not allow implicit any.Mike S.

3 Answers

1
votes

It is true that interfaces dont exist at runtime, but you can still iterate over properties of an existing object from that interface.

Please see my answer here How to loop though Record<K, T> for ways to iterate through an object

1
votes

You can just say to typescript that you're sure that key is keyof Filterdata :

for (const key in filterSettings) {
  filterString += `${key}_eq_${filterSettings[key as keyof FilterData]},`;
}

You can either set noImplicitAny: false in your tsconfig.json

0
votes

Indeed, the interface doesn't exist at runtime. You have to hardcode the properties that you want - the object that implements the interface might have any other properties as well:

const filterSettings: FilterData;

for (const key of ['variables', 'processDefinitionKey']) {
  filterString += `${key}_eq_${filterSettings[key]},`;
}