如何在 TypeScript 中断言 HTMLElement 的类型? [英] How to assert a type of an HTMLElement in TypeScript?
本文介绍了如何在 TypeScript 中断言 HTMLElement 的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试这样做:
var script:HTMLScriptElement = document.getElementsByName("script")[0];
alert(script.type);
但它给了我一个错误:
Cannot convert 'Node' to 'HTMLScriptElement': Type 'Node' is missing property 'defer' from type 'HTMLScriptElement'
(elementName: string) => NodeList
除非我将其强制转换为正确的类型,否则我无法访问脚本元素的类型"成员,但我不知道如何执行此操作.我搜索了文档 &样品,但我找不到任何东西.
I can't access the 'type' member of the script element unless I cast it to the correct type, but I don't know how to do this. I searched the docs & samples, but I couldn't find anything.
推荐答案
TypeScript 使用 '<>' 来包围强制转换,所以上面变成了:
TypeScript uses '<>' to surround casts, so the above becomes:
var script = <HTMLScriptElement>document.getElementsByName("script")[0];
但是,不幸的是你不能这样做:
However, unfortunately you cannot do:
var script = (<HTMLScriptElement[]>document.getElementsByName(id))[0];
你得到错误
Cannot convert 'NodeList' to 'HTMLScriptElement[]'
但是你可以这样做:
(<HTMLScriptElement[]><any>document.getElementsByName(id))[0];
这篇关于如何在 TypeScript 中断言 HTMLElement 的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文