-1

I want to use this generic helper function to create form data:

function createFormData(data: any): FormData {
  const formData = new FormData();

  for (const key in data) {
    formData.append(key, data[key]);
  }

  return formData;
}

But the ESLint gives me an unexpected any warning. When I change the parameter type any to object it shows me the following error message for data[key]:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'. No index signature with a parameter of type 'string' was found on type '{}'

How can I fix my code here in order that no error messages or warnings are shown (without just turning off the linter)?

2

1 Answer 1

0

Instead of any you could provide the value data type also

function createFormData(data: {[key: string]: any}): FormData {
  const formData = new FormData();

  for (const key in data) {
    formData.append(key, data[key]);
  }

  return formData;
}
Sign up to request clarification or add additional context in comments.

7 Comments

The ESLint warning unexpected any is still shown
So you are telling me, because they did it in that example project, it's the right way to go?
This is what i have created, also i think you need to define type for you data and if it throws error for using key as a string you might have to add the type of keys as string
The key: string part is fine. But it shows a warning because of the any keyword.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.