Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does assignment with arrows < type > mean in TypeScript?

I know that colon sets the type for the variable, but what does assignment with arrows mean with the type provided?

const mainVideo: HTMLVideoElement = <HTMLVideoElement> document.getElementById('mainVideo');

I was using mainVideo : HTMLVideoElement = document.getElementById('mainVideo') at first, but it wouldn't let me use any of the methods on the element, but assigning mainVideo with the arrows makes everything work. Wondering why that is and what's it called.

like image 281
a_byte_of_pizza Avatar asked Feb 24 '26 21:02

a_byte_of_pizza


1 Answers

It's called type assertion.

Think of type assertion as a way to make an entity type more specific by overriding it.

// this is an Element
let element = document.querySelector("#list");


// but I can make it more specific, by overriding its type
let element = <HTMLElement> document.querySelector("#list");

You can also use this other syntax:

let element = document.querySelector("#list") as HTMLElement;

Be careful. You don't want type assertion everywhere, just where it's necessary. Otherwise, your code may need refactoring.

Also, not always you can do type assertion. Only when either types sufficiently overlaps with the other. So, if you write this:

let element = document.querySelector("#list") as String;

VSCode says:

Conversion of type 'Element' to type 'String' may be a mistake because neither type sufficiently overlaps with the other.

Type 'Element' is missing the following properties from type 'String': charAt, charCodeAt, concat, indexOf, and 34 more

One way to make sure you can do this weird assertion is by converting the expression to unknown first:

let element = document.querySelector("#list") as unknown as String;

Even though it works, make sure YOU KNOW it's worth it.


What happend in your use case is that getElementById is a method which returns an HTMLElement and not, specifically, an HTMLVideoElement.

// it could be HTMLDivElement or HTMLInputElement, for example.
Document.getElementById(elementId: string): HTMLElement

Hence, when you did type assertion, you were basically saying:

I KNOW this method will return a more specific version of HTMLElement, called HTMLVideoElement.

like image 67
unsocialcattle Avatar answered Feb 27 '26 01:02

unsocialcattle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!