TypeScript-DOM-lib-generator icon indicating copy to clipboard operation
TypeScript-DOM-lib-generator copied to clipboard

fix: add FormData to URLSearchParams constructor

Open keithamus opened this issue 5 years ago • 13 comments

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.

keithamus avatar Jul 01 '20 09:07 keithamus

FormData can look like Record<string, string | File> (spec), not just Record<string, string>, so adding this is not valid in general.

niklasf avatar Sep 08 '20 09:09 niklasf

@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"

WesleySmits avatar Sep 17 '20 05:09 WesleySmits

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

saschanaz avatar Sep 26 '20 23:09 saschanaz

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.

stefanprobst avatar Oct 20 '20 16:10 stefanprobst

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.

niklasf avatar Oct 20 '20 16:10 niklasf

One way could be making FormData generic. FormData<string> should be always safe then.

saschanaz avatar Oct 20 '20 17:10 saschanaz

Any updates on this?

dylhack avatar Feb 22 '24 19:02 dylhack