Does anyone know how to cast in TypeScript?
I\'m trying to do this:
var script:HTMLScriptElement = document.getElementsByName(\"script\")[0];
alert(s
To end up with:
Array
object (not a NodeList
dressed up as an Array
)HTMLElements
, not Node
s force-casted to HTMLElement
sTry this:
let nodeList : NodeList = document.getElementsByTagName('script');
let elementList : Array<HTMLElement> = [];
if (nodeList) {
for (let i = 0; i < nodeList.length; i++) {
let node : Node = nodeList[i];
// Make sure it's really an Element
if (node.nodeType == Node.ELEMENT_NODE) {
elementList.push(node as HTMLElement);
}
}
}
Enjoy.
Since it's a NodeList
, not an Array
, you shouldn't really be using brackets or casting to Array
. The property way to get the first node is:
document.getElementsByName(id).item(0)
You can just cast that:
var script = <HTMLScriptElement> document.getElementsByName(id).item(0)
Or, extend NodeList
:
interface HTMLScriptElementNodeList extends NodeList
{
item(index: number): HTMLScriptElement;
}
var scripts = <HTMLScriptElementNodeList> document.getElementsByName('script'),
script = scripts.item(0);
Just to clarify, this is correct.
Cannot convert 'NodeList' to 'HTMLScriptElement[]'
as a NodeList
is not an actual array (e.g. it doesn't contain .forEach
, .slice
, .push
, etc...).
Thus if it did convert to HTMLScriptElement[]
in the type system, you'd get no type errors if you tried to call Array.prototype
members on it at compile time, but it would fail at run time.
This seems to solve the problem, using the [index: TYPE]
array access type, cheers.
interface ScriptNodeList extends NodeList {
[index: number]: HTMLScriptElement;
}
var script = ( <ScriptNodeList>document.getElementsByName('foo') )[0];
Could be solved in the declaration file (lib.d.ts) if TypeScript would define HTMLCollection instead of NodeList as a return type.
DOM4 also specifies this as the correct return type, but older DOM specifications are less clear.
See also http://typescript.codeplex.com/workitem/252
You always can hack type system using:
var script = (<HTMLScriptElement[]><any>document.getElementsByName(id))[0];