Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: Work around type definition error for javascript builtin

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?

like image 698
Joe Avatar asked Sep 30 '22 04:09

Joe


2 Answers

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);
like image 54
basarat Avatar answered Oct 07 '22 20:10

basarat


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

like image 27
Scott Crowder Avatar answered Oct 07 '22 21:10

Scott Crowder