Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying to Eclipse/JSDT the type of a Javascript variable

I'm trying to use Eclipse for some server-side Javascript development.

The API I use has a function doStuff(string, object) (names changed to protect the guilty) that returns a value of differing types (subclasses of one type) depending on the (values of) the arguments passed it.

I have built a Javascript library to describe this function:

/**
  * function doStuff(s, o)
  * @memberOf Global
  * @param {String} s
  * @param {Object} o
  * @type ResultType
  * @returns {ResultType}
  */
doStuff = function(str, obj} {return new ResultType();}

Because it can return several types, I have declared it as returning the base type. However, that means Eclipse doesn't know what type it really is, and so I get later spurious errors when trying to access fields of that object.

So there can be FooResultType, BarResultType, each of which are ResultTypes, but have additional fields/functions

Is there any way around this? Can I somehow annotate the variable holding the returned value so that Eclipse knows what type it really is?

I've tried (with and without braces around FooResultType)

/**
  * @type FooResultType
  */
  v = doStuff("stringvalue", someObject);

but this makes no difference.

(There are other questions in this area, but nothing that address this issue, I think)

like image 725
The Archetypal Paul Avatar asked Jul 03 '11 17:07

The Archetypal Paul


People also ask

How does JavaScript interpreter determine a variable data type?

JavaScript uses dynamic typing, and therefore this means that the JavaScript engine will choose the best data type for your variable based on its value.

What type of variable can be stored in JavaScript?

JavaScript is a "dynamically typed language", which means that, unlike some other languages, you don't need to specify what data type a variable will contain (numbers, strings, arrays, etc.).

Is this a variable in JavaScript?

In JavaScript, “this” variable is a variable that every execution context gets, in a regular function call. Every JavaScript function has a reference to its current execution context while executing, called this.


1 Answers

(Answering my own question)

The below does work. The key seems to be the "var" - only by declaring a variable can you get JSDT to recognise it has the specified type. My suspicion is that JSDT can only manage one type per variable, although of course being Javascript the type can change arbitarily.

/**
  * @returns {FooResultType}
  */
  var v = doStuff("stringvalue", someObject);

It also seems to require @returns rather than @type, although it's difficult to know what is and is not supported by JSDT - it's not well documented and experimentation is needed. Small changes seem to make unexpected differences sometimes.

like image 196
The Archetypal Paul Avatar answered Nov 15 '22 01:11

The Archetypal Paul