5

I want to use FormData in typescript. Unfortunately, the generated typescript definition files doesn't support a FormData constructor with a Form Element as detailed in Typescript Issue #1074.

I have the following code:

var formEl = <HTMLFormElement> document.getElementById("myForm");
var formData = new FormData(formEl);

The code gives the following error because the generated definition is wrong:

error TS2346: Supplied parameters do not match any signature of call target.

I want to use the following declaration:

declare var FormData: {
    prototype: FormData;
    new (form?: HTMLFormElement): FormData;
}

But, if I include that type definition, I get this error:

error TS2403: Subsequent variable declarations must have the same type. Variable 'FormData' must be of type '{ new (): FormData; prototype: FormData; }', but here has type '{ new (form?: HTMLFormElement): FormData; prototype: FormData; }'.

How can I work around this issue?

3 Answers 3

3

How can I work around this issue?

Potential 1:

Send a PR.

Potential 2:

Update the shipped lib.d.ts in place:

declare var FormData: {
    prototype: FormData;
    new (form?: HTMLFormElement): FormData;
}

Potential 3:

Copy and customize lib.d.ts and compile with --noLib and manually reference your custom lib.d.ts.

Potential 4:

Bypass the type-checker

var formEl = <HTMLFormElement> document.getElementById("myForm");
var formData = new window['FormData'](formEl);
Sign up to request clarification or add additional context in comments.

1 Comment

Bummer, I was hoping I could just include the new declaration.
1

There is a bug in the VS2017 typescript libraries (which may have been fixed in the April 2017 update). You can around the error you noted by turning off the LanguageService in Tools|Options|Text Editor|JavaScript/TypeScript|LanguageService Just uncheck the "Enable the new JavaScript language service." checkbox.

More details of the issue are on https://developercommunity.visualstudio.com/content/problem/25310/unload-projects-hangs-on-close-solution.html

Comments

0

There's already a bug on GitHub. It's targeted for fixing in TypeScript 1.6.

Until then, this is a simple workaround in TypeScript:

var formEl = <HTMLFormElement> document.getElementById("myForm");
var formData = <FormData> new (<any> FormData) (formEl);

And the generated javascript, just what you wanted:

var formData = new FormData(formEl);

This should keep working even after they fix the lib.d.ts issue.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.