Casting with JSDoc

868 views
Skip to first unread message

Ross Goldberg

unread,
Feb 4, 2013, 6:28:15 AM2/4/13
to closure-comp...@googlegroups.com
I'd like to be able to perform the equivalent of a cast in JSDoc.

e.g., I have the following JSDoc / JS:

/**@type{!HTMLOptGroupElement}*/
var og = document.createElement('optgroup');

The compiler warns correctly warns:

JSC_TYPE_MISMATCH: initializing variable
found   : Element
required: HTMLOptGroupElement

How can I perform a "cast" into an HTMLOptGroupElement from the Element returned from document.createElement('optgroup')?

Logically, I'd want something like a @cast annotation, that could look like:

var og = /**@cast{!HTMLOptGroupElement}*/ document.createElement('optgroup');

Thanks.

Tom Payne

unread,
Feb 4, 2013, 7:57:28 AM2/4/13
to closure-comp...@googlegroups.com
var og = /** @type {!HTMLOptGroupElement} */ (document.createElement('optgroup'));

Note brackets around expression being typecast.



--
 
---
You received this message because you are subscribed to the Google Groups "Closure Compiler Discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email to closure-compiler-d...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Ross Goldberg

unread,
Feb 4, 2013, 3:33:50 PM2/4/13
to closure-comp...@googlegroups.com, t...@tompayne.org
Thanks.

Tom Payne

unread,
Feb 4, 2013, 3:45:15 PM2/4/13
to closure-comp...@googlegroups.com
Following up on this, casting the result of document.createElement, goog.dom.createElement, canvas.getContext, and similar examples is so common that it would be wonderful if the Closure Compiler could automatically type the return value of these commonly-used functions, where it can reasonably do so.

i.e., it would be wonderful if
  document.createElement('optgroup')
magically returned a "HTMLOptGroupElement", but there is no expectation that
  document.createElement(someExpression)
would do any type refinement.

This could break existing code like:

  var element;
  element = document.createElement('optgroup');
  // do something with element as an HTMLOptGroupElement
  // ...
  element = document.createElement('div');
  // do something with element as an HTMLDivElement

but I hope that such code is rare, and a simple variable rename is all that is required in any case.

Regards,
Tom
  
Reply all
Reply to author
Forward
0 new messages