简体   繁体   English

向 Eclipse/JSDT 指定 Javascript 变量的类型

[英]Specifying to Eclipse/JSDT the type of a Javascript variable

I'm trying to use Eclipse for some server-side Javascript development.我正在尝试将 Eclipse 用于某些服务器端 Javascript 开发。

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.我使用的 API 有一个 function doStuff(string, object) (更改名称以保护有罪),它返回不同类型的值(一种类型的子类),具体取决于传递的 ZDBC11CAABD5BDA99E7D786 的(值)。

I have built a Javascript library to describe this function:我建立了一个 Javascript 库来描述这个 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.但是,这意味着 Eclipse 不知道它到底是什么类型,所以我后来在尝试访问该 object 的字段时会遇到虚假错误。

So there can be FooResultType, BarResultType, each of which are ResultTypes, but have additional fields/functions所以可以有FooResultType,BarResultType,每一个都是ResultTypes,但是有额外的字段/函数

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?我可以以某种方式注释保存返回值的变量,以便 Eclipse 知道它到底是什么类型吗?

I've tried (with and without braces around FooResultType)我已经尝试过(在 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) (这方面还有其他问题,但我认为没有什么可以解决这个问题)

(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.关键似乎是“var”——只有声明一个变量才能让 JSDT 识别它具有指定的类型。 My suspicion is that JSDT can only manage one type per variable, although of course being Javascript the type can change arbitarily.我怀疑 JSDT 每个变量只能管理一种类型,尽管当然是 Javascript 类型可以任意更改。

/**
  * @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.它似乎也需要@returns 而不是@type,尽管很难知道 JSDT 支持和不支持什么 - 它没有很好的文档记录,需要进行实验。 Small changes seem to make unexpected differences sometimes.有时,微小的变化似乎会产生意想不到的差异。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM