TypeScript: CheckJS cannot cast `Element` to `HtmlElement` types

TypeScript Version: 2.4.2

Code For this JavaScript with checkJs enabled:

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

Expected behavior: Can cast result of document.querySelector which returns an Element to an HTMLImageElement

Actual behavior: Error:

file: 'file:///Users/matb/projects/san/a.js'
severity: 'Error'
message: 'Type 'Element' is not assignable to type 'HTMLImageElement'.
  Property 'align' is missing in type 'Element'.'
at: '5,7'
source: 'js'

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 1
  • Comments: 19 (9 by maintainers)

Most upvoted comments

@thw0rted

var x = document.querySelector("#foo");
if (x instanceof HTMLImageElement) {
    x.src = "whatever";
}

Is already interpreted and typechecked correctly today.

This worked for me 😃

(document.querySelectorAll('.primary-menu > ul > li') as any as HTMLLIElement[])

@jcready Only if the strictNullChecks compiler flag is true.