I have a simple question and I am new to TS. Could not find any clear explanation anywhere which is surprising.
What is the main difference between telling TS the type this way:
const ul = document.querySelector('#nav') as HTMLUListElement;
and this way:
const ul: HTMLUListElement = document.querySelector('#nav');
It seems like TS recognizes the type and gives me IntelliSens in both situations. If so, why do I need to use type casting here as it is suggested by other developers?
Thanks in advance.
“The querySelector method returns Element | null.” https://stackoverflow.com/a/43035645/12239744
when using ‘as’ you force right side value to this cast.
But “:HTMLUlistElement” only works when this is inherited class of Element class. You can see the structure of htmlelement https://developer.mozilla.org/en-US/docs/Web/API/HTMLUListElement
queryselector returns Element, so we can use “: HTMLUListElement” If this returns any or AppleClass, you can not use this method. You should use “as” but If you are not aware of what is the return type of exactly. “As” can be dangerous. You can cast an AppleClass to HtmlElement but this object may not have necessary properties.
I think that “as” is not good for your case, the other is better.
Edit: https://www.typescripttutorial.net/typescript-tutorial/type-casting/ Usage of “ : HTMLUListElement” is down casting.
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