Skip to content
Advertisement

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?

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement