2

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)?

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much for your answer! The workaround worked perfectly. Good to know that you are working to solve this problem. Anyway, keep up the good work, as Visual Studio Code is a great lightweight code editor to work with JavaScript! :)
As of today, var App = { canvas: document.getElementsByTagName('canvas')[0] } doesn't seem to work for me... The workaround kinda works, I am using VS Code 1.45.1 on OS X...
It's been 4 years. When is this going to be fixed??

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.