Skip to content

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

Closed
@thw0rted

Description

@thw0rted
  • 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?

Metadata

Metadata

Assignees

Labels

*questionIssue represents a question, should be posted to StackOverflow (VS Code)javascriptJavaScript support issues

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions