DEV Community

Discussion on: FormData in TypeScript

Collapse
 
foresthoffman profile image
Forest Hoffman • Edited

Could you use the FormData.entries() method? developer.mozilla.org/en-US/docs/W...

It appears to return key-value pairs that you can iterate over.

e.g.

const data = new FormData(form);
const entries = data.entries();
for (let entry of entries) {
  const key = entry[0];
  const val = entry[1];
  console.log(key, val);
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
deciduously profile image
Ben Lovy • Edited

That's what I couldn't get working. The above code was not accepted by the TS compiler, complaining that there is no such property entries.

edit: when I say not accepted, it does compile because it's TypeScript. It flags the line with an error, and the code block simply does not execute. Nothing gets logged to the console.

Collapse
 
foresthoffman profile image
Forest Hoffman

Hmm, that is odd. I saw a TS issue related to this, github.com/Microsoft/TypeScript/is.... Someone suggested using Array.from() to mitigate this.

e.g.

form.onsubmit = (event) => {
    const data = new FormData(form);
    const pairs = Array.from(data.entries());
    for (let pair of pairs) {
        console.log(pair);
    }
};
Thread Thread
 
deciduously profile image
Ben Lovy

Interesting - thank you for the issue link, I'll give it a whirl when I get back to my computer. I missed that one when searching it myself.

In that conversation, though, they mention needing to use a target < es2015 - I did try doing that instead to no avail. If Array.from() solves the issue, though, it's a small price to pay, I don't think it's any less readable.

Thread Thread
 
deciduously profile image
Ben Lovy

Ah - another comment in that thread had the fix. You need to add "dom.iterable" to your libs in tsconfig - I'll update the post. Thank you thank you!

Thread Thread
 
foresthoffman profile image
Forest Hoffman

My pleasure! Glad it's fixed 😀