fix: add FormData to URLSearchParams constructor
See https://github.com/microsoft/TypeScript/issues/30584
I'm aware that URLSearchParams also accepts generic iterators (see https://github.com/microsoft/TSJS-lib-generator/issues/741) but mostly interested in getting this specific pattern fixed quickly, as it's used a lot.
FormData can look like Record<string, string | File> (spec), not just Record<string, string>, so adding this is not valid in general.
@sandersn In your example the form doesn't have any form field values to map to the URLSearchParams. See the following example:
const form = document.createElement('FORM');
const field = document.createElement('input');
field.name = 'fieldName';
field.value = 'fieldValue';
form.appendChild(field);
const formData = new FormData(form);
const urlSearchParams = new URLSearchParams(formData);
urlSearchParams.toString(); // "fieldName=fieldValue"
Shorter:
const f = new FormData();
f.append('foo', 'bar');
new URLSearchParams(f).toString(); // foo=bar
In the case of blobs it does still work, but in broken way:
const f = new FormData();
f.append('foo', new Blob(['bar']));
new URLSearchParams(f).toString(); // foo=%5Bobject+File%5D
it would be great to get this in, as this pattern is quite prominently referred to already in the third sentence in the mdn entry on FormData.
Allowing this without a type assertion would be somewhat inconsistent. It's like changing
interface URLSearchParams {
set(name: str, value: str)
}
to
interface URLSearchParams {
set(name: str, value: any /* !* /)
}
just because any value will be coerced to a string, like {} is coerced to [object Object], or a file is coerced to [object File] as saschanaz found.
One way could be making FormData generic. FormData<string> should be always safe then.
Any updates on this?