Typescript form reset() not working

2020-03-25 15:01发布

I'm using typescript to reset a form but it's not working or typescript compiler (1.0.3 version) doesn't recognize reset() function. Compiler gives Error

Build: Interface 'HTMLFormElement' incorrectly extends interface 'HTMLElement'. C:\Program Files (x86)\Microsoft SDKs\TypeScript\1.4\lib.d.ts

This is the typescript code

var resetForm =document.getElementById(dirtyFormID);
resetForm.reset();

When I copied above code to js file, it's working perfectly.

What's the reason for it?

3条回答
一夜七次
2楼-- · 2020-03-25 15:30

Since the function getElementById returns a more generic type HTMLElement you need to assert the specific version manually :

var dirtyFormID = 'something';
var resetForm = <HTMLFormElement>document.getElementById(dirtyFormID);
resetForm.reset();
查看更多
啃猪蹄的小仙女
3楼-- · 2020-03-25 15:48

With typescript.

to avoid Google Chrome Error "resetForm.reset is not a function", I specified the type of my button element, "reset" in my HTML code. Having specified a:

type = 'reset'

make my function works very well.

查看更多
虎瘦雄心在
4楼-- · 2020-03-25 15:51

Please note that document.getElementById returns HTMLElement (like already said here). You should cast your HTMLElement to HTMLFormElement

The casting should be like this:

var resetForm:HTMLFormElement;
resetForm= <HTMLFormElement>document.getElementById('your form id');
if(resetForm)
    resetForm.reset();
查看更多
登录 后发表回答