Intellisense in the return of Javascript function in Vscode

Asked

Viewed 51 times

0

How to make Vscode show the Intellisense in callback using method Map.prototype.get?

Code:

function tanque(altura){
  this.altura = altura;
}

let objMap = new Map();
objMap.set('7101', new tanque(101));

let t7101 = objMap.get('7101');
let tt701 = new tanque(102)

t7101.

And the screenshot (note that the Intellisense it’s not much help):

Demonstração do mau intellisense

The object t7101 should show in the Intellisense the property altura. How to make this possible?

1 answer

1


You can use a Jsdoc comment for this. See:

function tanque(altura) {
  this.altura = altura;
}

/** @type {Map<string, tanque>} */
const objMap = new Map();

Basically, according to the definition of types, Map is generic. The first generic "argument" is the type of map keys and the second, the type of values each key will store. In that case, how are you utilizing string for keys and tanque for values, it is made Map<string, tanque>.

See the definition of types for Map here.


Jsdoc is relatively well supported by Vscode (through language server from Typescript itself) to provide certain support for Javascript. Of course it will not prevent you from doing something "statically" incorrect in relation to the type. For this kind of thing, use the Typescript.

However, it is useful to help with the Intellisense. See in your example:

Demonstração do intellisense

Learn more about the Jsdoc on the official website. In the previous example I used the tag @type, but there are several others as well. And here is the list of tags Jsdoc that Typescript supports (and therefore can be used to help develop Javascript in Vscode).

See that you can go further and use the tag @param to set the type of the parameter altura. You can also set the property type altura:

/**
 * @param {string} altura
 */
function tanque(altura) {
  /** @type {string} */
  this.altura = altura;
}

But if you go to use Jsdoc extensively, it can harm the readability of the code. That much comment is ugly. In this case, it may be good to consider using Typescript, which brings several other benefits, such as the security of a statically typed language.

  • 1

    Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.