Search code examples
javascriptintellij-ideawebstormtype-hinting

Is there a way to hint the passed argument type to IDE (in my case Webstorm) in Javascript?


I have the following HTML file with some JavaScript in it:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Index</title>
</head>
<body>
<div id="root"></div>
<div>
    <label for="new-content">
        <textarea id="new-content" style="width: 400px; height: 100px"></textarea>
    </label>
    <br/>
    <button onclick="addContent(document.getElementById('new-content'))">Submit</button>
</div>


<script>
    function addContent(/*HTMLTextAreaElement*/content) {
        alert(content.value);
    }
</script>
</body>
</html>

I like how I can hint Webstorm (or IntelliJ or Eclipse) what is the type of content is in function addContent, but I do not like how I can not tell what it is in onclick, which leads to following warning:

enter image description here

Here is my first world problem: Can I hint the type of document.getElementById('new-content') in the argument?


Solution

  • I figured out a way by trial and error, the following seems to work:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Index</title>
    </head>
    <body>
    <div id="root"></div>
    <div>
        <label for="new-content">
            <textarea id="new-content" style="width: 400px; height: 100px"></textarea>
        </label>
        <br/>
        <button onclick="addContent(getNewContent())">Submit</button>
    </div>
    
    <div id="content"></div>
    
    <script>
        function getNewContent() {
            return document.getElementById('new-content');/*HTMLTextAreaElement*/
        }
    
        function addContent(/*HTMLTextAreaElement*/content) {
            document.getElementById('content').innerHTML =
                document.getElementById('content').innerHTML +
                '<p>'.concat(content.value).concat('</p>');
        }
    </script>
    </body>
    </html>