Argument of type ‘FormData’ is not assignable to parameter of type ‘string | string[][] | Record | URLSearchParams | undefined’.

It’s very disappointing when you find this issue was there for 5 years and it was Closed without being resolved.

Here’s the full error as shown by TypeScript:

const fd = new FormData(form);
const values = new URLSearchParams(fd).toString();

Argument of type 'FormData' is not assignable to parameter of type 'string | string[][] | Record<string, string> | URLSearchParams | undefined'.
Type 'FormData' is missing the following properties from type 'URLSearchParams': size, sort   ts(2345)

Everything seems fine according to the URLSearchParams spec, yet TypeScript thinks you are the one who is wrong (thank you, Microsoft, another very smart decision).

Solution

Override the type of FormData that you pass into a URLSearchParams constructor:

const fd = new FormData(form);
const values = new URLSearchParams(fd as unknown as Record<string, string>).toString();

If you need key-value pairs (to be JSONified), use Object.fromEntries:

const fd = new FormData(form);
const values = Object.fromEntries(new URLSearchParams(fd as unknown as Record<string, string>));

Did you know that I made an in-browser image converter, where you can convert your images without uploading them anywhere? Try it out and let me know what you think. It's free.

Leave a Comment

Your email address will not be published. Required fields are marked *