I'm liking typescript so far, but find that i need to do type assertion a lot. For example casting an EventTarget to an HTMLAnchorElement is a common use case for me. However to get that, i need to use something like the following:
getTabID(eventTarget: EventTarget) : string {
// without the following variable, the compiler tells me that .hash
// is not a property of EventTarget, which according to the interface, it isn't.
// So thats fine, i'll cast it to an Element
let mEventTarget: HTMLAnchorElement = <HTMLAnchorElement>eventTarget
let mTabID: string
if(mEventTarget.hash){
mTabID = mEventTarget.hash.split('#')[1]
}
return mTabID
}
However this means that if I don't want the compiler to throw errors I need to create variables in my functions JUST to do type assertions. I don't mind the extra typing, but these end up in the JS as well and ends up wasting bytes in my js files.
I would like to be able to the following:
getTabID(eventTarget: EventTarget) : string {
let mTabID: string
// Do the type assertion in the parameter
if(<HTMLAnchorElement> eventTarget.hash){
mTabID = mEventTarget.hash.split('#')[1]
} else {
mTabID = mEventTarget.dataset.tabId
}
return mTabID
}
I've had a good look in the docs and SO and can't seem to find any way to do this. Anyone have any ideas?
eventTarget
will always be aHTMLAnchorElement
, why not declareeventTarget: HTMLAnchorElement
in the parameter and force callers ofgetTabID
to ensure that it isHTMLAnchorElement
? – SaravanaeventTarget: EventTarget | HTMLAnchorElement
as type, which enables both EventTarget and HTMLAnchorElement as types. – SpitzbuebEventTarget
to a function that expects anHTMLAnchorElement
. @Wernerson I suppose that would stop the errors, but seems like a hack. – C02EquinoxgetTabID(target as HTMLAnchorElement)
. If all this feels like a hassle, I would just type the parameter withany
:(eventTarget: any)
to turn off type checking. – Saravanaas
syntax but couldn't figure out where to use it. Perfect! Thank you! – C02Equinox