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.
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, calledHTMLVideoElement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With