user1945293
user1945293

Reputation: 197

Visual Studio Code JavaScript Intellisense not working for objects properties

I'm using Visual Studio Code 1.11.1.

For the following code, Intellisense works correctly, understanding that the canvas variable is of type HTMLCanvasElement:

var canvas = document.getElementsByTagName('canvas')[0];

In fact, when I write the name of that variable followed by a dot it shows me all properties and methods of HTMLCanvasElement.

However, using the following code, in which I wrap that variable inside an object (acting as a namespace), Intellisense doesn't understand anymore that the variable is of type HTMLCanvasElement:

// create a namespace "App"
var App;
App = {};

App.canvas = document.getElementsByTagName('canvas');

When I write "App.canvas" followed by a dot character, Intellisense doesn't show me all the properties and methods of HTMLCanvasElement. In fact, it considers App.canvas of type any.

I've tried also to use the @type annotation like in the following code, but the result is the same:

// create a namespace "App"
var App;
App = {};

/** @type {HTMLCanvasElement} */
App.canvas = document.getElementsByTagName('canvas')[0];

Is it possible to make Intellisense understand the variable types for properties of objects (like App.canvas in my example)?

Upvotes: 2

Views: 3093

Answers (1)

Matt Bierner
Matt Bierner

Reputation: 65593

I work on JS/TS support for VSCode. We use the TypeScript project to power both our JS and TS language support, so believe you are running into this bug: https://github.com/Microsoft/TypeScript/issues/10868

As a workaround, try declaring the type of canvas on App itself:

/** @type {{canvas:HTMLCanvasElement}} */
var App;
App = {};

App.canvas = document.getElementsByTagName('canvas')[0];

Using an object literal should also work:

var App = { canvas: document.getElementsByTagName('canvas')[0] }

We're looking into improving IntelliSense in these cases

Upvotes: 2

Related Questions