Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over Typescript interface properties?

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?

like image 587
Karen Avatar asked Oct 24 '25 21:10

Karen


1 Answers

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

like image 135
diouze Avatar answered Oct 26 '25 11:10

diouze