简体   繁体   中英

TS(7015) in a document.form : "Element implicitly has an 'any' type because index expression is not of type "number"

I am trying to get values entered by a user in a form.

This is how my form looks like:

<form name="myForm">
   <span class="myFormSpan">+</span>
   <input type="text" placeholder="My answer" name="myFormUserInput">
   <button type="button" class="formButton">Ok</button>
</form>

I want to get what the user's put in the input form, so my typescript code looks like this:

formInputs.addEventListener("click", () => {
   const userInput: any = document.forms["myForm"].elements["myFormUserInput"].value;
   console.log(userInput);
});

which works fine, except that I keep getting a TypeScript warning ts(7015): Element implicitly has an 'any' type because index expression is not of type 'number'. . I've tried to change my code to document.forms[0] , which doesn't remove the warning, and tried to add some type specifications here and there without being more successful...

I would like to keep implicit warning on (contrary to the solution written there: Element implicitly has an 'any' type ) because I would like to understand the issue and have a way to solve it

Any idea?

Thanks a lot !

Using number-based indexes on forms and elements should clear the warning.

formInputs.addEventListener("click", () => {
    const userInput: any = (document.forms[0].elements[0] as HTMLInputElement).value;
    console.log(userInput);
});

But you should realy consider to use document.querySelector()

This will find the correct form/input regardless of position or order inside the DOM

like so:

formInputs.addEventListener("click", () => {
    const userInput = document.querySelector<HTMLInputElement>('form[name="myForm"] input[name="myFormUserInput"]') || null

    if (userInput !== null)
        console.log(userInput.value);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM