我试图从DOM中选择一个锚,但总是告诉我它不包含锚的属性,如下载,字符集等
interface myLinkType extends HTMLAnchorElement {}
const myLink: myLinkType(that gives error) = document.getElementById('mylink')
为什么TypeScript会抱怨:
- getElementById可以返回锚之外的其他元素。这就是为什么错误信息是:
Type 'HTMLElement | null' is not assignable to type 'HTMLAnchorElement | null'
。如果您意外地将id="mylink"
放在按钮上,则该按钮将没有锚定属性,例如charset等。错误信息为:Type 'HTMLElement' is missing the following properties from type 'HTMLAnchorElement': charset, coords, download, hreflang, and 21 more.
. - getElementById也不能保证找到一个元素。如果找不到元素,则返回null。
TypeScript试图强迫你的程序在访问这些属性之前检查getElementById是否找到了一个元素,并且这个元素实际上是一个锚。这样做是为了防止运行时错误。
这是有效的,因为它只能返回一个锚元素:
const a: HTMLAnchorElement | null = document.querySelector('a#mylink')