Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How do I handle type assertion in vanilla Javascript when using checkJs? #31590

Closed
thw0rted opened this issue Jul 27, 2017 · 1 comment
Closed
Assignees
Labels
javascript JavaScript support issues *question Issue represents a question, should be posted to StackOverflow (VS Code)

Comments

@thw0rted
Copy link

thw0rted commented Jul 27, 2017

  • VSCode Version: Code 1.14.2 (cb82feb, 2017-07-19T23:26:08.116Z)
  • OS Version: Linux x64 4.10.0-27-generic

I've asked the same question on StackOverflow but I'm rephrasing it here. I'm worried that the answer to "how do I do this?" will wind up being "oh crap, you can't, we didn't think of that."

  1. Enable type checking on Javascript files (compilerOptions.checkJs=true in jsconfig.json)
  2. Write the following code in a .js file:
    let el = document.querySelector("#definitelyAnImage");
    el.src = "image.png";
  3. Notice that .src gets marked as an error -- this is because querySelector returns an Element but the .src property is defined on the subclass HTMLImageElement.

In Typescript, I gather the solution would be to use a type-assertion before accessing the subclass property, or use as HTMLImageElement in the initial assignment. What can I do to get rid of this error in vanilla JS?

@vscodebot vscodebot bot added the javascript JavaScript support issues label Jul 27, 2017
@mjbvz mjbvz added the *question Issue represents a question, should be posted to StackOverflow (VS Code) label Jul 27, 2017
@mjbvz
Copy link
Collaborator

mjbvz commented Jul 27, 2017

You should be able to use @type in the jsdocs:

/**
 * @type {HTMLImageElement}
 */
const el = document.querySelector("#definitelyAnImage");
el.src = "image.png";   

However it seems like there is a bug that prevents this from working properly. I've opened microsoft/TypeScript#17453 to track this

@mjbvz mjbvz closed this as completed Jul 27, 2017
@vscodebot vscodebot bot locked and limited conversation to collaborators Nov 17, 2017
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
javascript JavaScript support issues *question Issue represents a question, should be posted to StackOverflow (VS Code)
Projects
None yet
Development

No branches or pull requests

2 participants