Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript type annotations

I'm using WebStorm and encountering the following problem:

/** @type {HTMLCanvasElement} */
var buffered_canvas = document.createElement("canvas");
buffered_canvas.width = 256;
buffered_canvas.height = 256;

When I annotate buffered_canvas as type HTMLCanvasElement, it complains that createElement returns an HTMLElement which cannot be assigned to an HTMLCanvasElement.

/** @type {HTMLElement} */
var buffered_canvas = document.createElement("canvas");
buffered_canvas.width = 256;
buffered_canvas.height = 256;

When I change it to type HTMLElement, it complains instead that width and height properties are undefined on HTMLElement.

How do I do this properly?

Also -- I'm new to JavaScript and having trouble finding any real specification of things like HTMLElement and what properties it has or method signatures for createCanvas and what type it returns. Sometimes I find decent stuff on MDN, but they don't usually include method signatures or much type information. Is there any good resource for this stuff?

Thanks

like image 319
user202987 Avatar asked Jan 10 '23 06:01

user202987


1 Answers

You can type cast like this:

var buffered_canvas = /** @type {HTMLCanvasElement} */ (document.createElement("canvas"));

See the bottom of this page.

You can use this along with the regular type annotation, like this.

/** @type {HTMLCanvasElement} */
var buffered_canvas = /** @type {HTMLCanvasElement} */ (document.createElement("canvas"));

If WebStorm follows the same annotation conventions as Closure this should work.

having trouble finding any real specification of things like HTMLElement and what properties it has or method signatures for createCanvas and what type it returns.

MDN is good, you can also look at WHATWG and W3C for standards.

like image 114
Dagg Nabbit Avatar answered Jan 17 '23 18:01

Dagg Nabbit