简体   繁体   中英

Property 'content' does not exist on type 'HTMLElement' in Typescript

I get error when I try to get the content of meta tag:

document.getElementById('mymetatag').content

in Javascript is works, but typescript say that

Property 'content' does not exist on type 'HTMLElement'

So how to extend the HTMLElement type interface to support content property?

TypeScript doesn't know what kind of element has this specific ID. It cannot trust the element even exists to begin with!

You need to introduce another check in order to validate your assumption:

const element: HTMLElement | null = document.getElementById('mymetatag');

if (element instanceof HTMLMetaElement) {
  element.content;
}

Update

You can also use assertion signatures.

function assert(condition: boolean, message: string): asserts condition {
  if (!condition) {
    throw new Error(message);
  }
}

Then your solution becomes:

const element: HTMLElement | null = document.getElementById('mymetatag');

assert(element instanceof HTMLMetaElement, "A <meta> element of id 'mymetatag' needs to exist in the DOM.");

element.content; // string

document.getElementById() returns an HTMLElement . But you know that your result is a meta tag, which is a type of HTMLMetaElement . Looking at the docs you can see that HTMLElement is the ancestor of HTMLMetaElement so you should downcast your element to this type. You can do this with two different syntaxes:

const metaElement = document.getElementById("mymetatag") as HTMLMetaElement;
// Or the second version:
//const metaElement = <HTMLMetaElement>document.getElementById("mymetatag");
const metaContent = metaElement.content;

See more about type assertions here .

Try following:

(<HTMLMetaElement> document.getElementById("mymetatag")).content;

Also, for <template id="source"> , you can use HTMLTemplateElement

const source = document.querySelector('#source') as HTMLTemplateElement;
const sourceClone = source.content.cloneNode(true) as HTMLElement;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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