How to get or access the properties and methods of link HTML element tags without errors in TypeScript?

Published September 26, 2021

To get or access the properties and methods of the link HTML element tags without having errors or red squiggly lines in TypeScript, you have to assert the type for the link HTML element tag using the HTMLLinkElement interface in TypeScript.

The errors or warnings are shown by the TypeScript compiler since the compiler doesn't know more information on the link HTML element tag ahead of time. But we know that we are referencing the link HTML tag and thus we can tell the compiler to use the HTMLLinkElement interface which contains the declarations for properties and methods.

TL;DR

// get reference to the first 'link'
// HTML element tag in the document
// with type assertion using the HTMLLinkElement interface
const linkTag = document.querySelector("link") as HTMLLinkElement;

// no errors or red squiggly lines will be
// shown while accessing properties or methods
// since we have asserted the type
// for the 'link' HTML element tag 😍
const href = linkTag.href;

To understand it better let's say we are selecting the first link HTML element tag using the document.querySelector() method like this,

// get reference to the first 'link'
// HTML element tag in the document
const linkTag = document.querySelector("link");

Now let's try to get the value of a property called href which is used in the link HTML element tag as an attribute.

It can be done like this,

As you can see that the TypeScript compiler is showing a red squiggly line below the linkTag object. If you hover over the linkTag you can see an error saying Object is possibly 'null'. This is because TypeScript is not sure whether the linkTag object will have properties and methods ahead of time.

Now to avoid this error we can assert the type for the link HTML element tag using the HTMLLinkElement interface in TypeScript.

To do Type assertion we can use the as keyword after the document.querySelector("link") method followed by writing the interface name HTMLLinkElement.

It can be done like this,

// get reference to the first 'link'
// HTML element tag in the document
// with type assertion using the HTMLLinkElement interface
const linkTag = document.querySelector("link") as HTMLLinkElement;

// no errors or red squiggly lines will be
// shown while accessing properties or methods
// since we have asserted the type
// for the 'link' HTML element tag 😍
const href = linkTag.href;

Now if hover over the href property in the linkTag object TypeScript shows more information about the property itself which is again cool and increases developer productivity and clarity while coding.

See the above code live in codesandbox.

That's all 😃!

Feel free to share if you found this useful 😃.


Share on: Facebook Twitter