Reputation: 176
I've got form in my angular project. And this form contains input with image upload. So I use FormData to send the data to server. I try to use function to append form fields to FormData.
export function toFormData<T>(formValue: T) {
const formData = new FormData();
for (const key of Object.keys(formValue)) {
const value = formValue[key]; <--- error here
formData.append(key, value);
}
return formData;
}
sendForm() {
const team = toFormData(this.form.value);
this.teamService.sendTeam(team).subscribe(() => {});
}
I've got an error from ts-lint "Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'unknown'. No index signature with a parameter of type 'string' was found on type 'unknown'". IDE underlines formValue[key] expression. Try to add types, but it didn't help.
Upvotes: 2
Views: 934
Reputation: 13539
formValue[key]
is any
because T
doesn't narrow types, that's fine.
To suppress this error you need to cast any
to unknown
like that T extends Record<string, unknown>
. Now it means value
has unknown type and it should be asserted first before usage of the variable.
export function toFormData<T extends Record<string, unknown>>(formValue: T) {
const formData = new FormData();
for (const key of Object.keys(formValue)) {
const value = formValue[key];
// feel free to remove Blob if it's not your case.
if (typeof value !== 'string' && !(value instanceof Blob)) {
continue;
}
formData.append(key, value);
}
return formData;
}
Upvotes: 2