Typescript type assertions in parameters
I like typescript but find that I need to do type assertion a lot. For example, using the EventTarget method on the HTMLAnchorElement is a common use case for me. However, in order to get this, 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 in order to make type assertions. I don't mind additional typing, but they end up in JS too and end up losing bytes in my js files.
I would like to be able to:
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 had a good look at the docs and SO and I can't seem to find a way to do this. Does anyone have any idea?
source to share
You can do inline type assertions by surrounding the assertion with parentheses:
if((<HTMLAnchorElement>eventTarget).hash) {
You can also see what you can do to prevent the need for a type assertion, for example:
getTabID(eventTarget: HTMLAnchorElement) : string {
let mTabID: string;
if(eventTarget.hash){
mTabID = eventTarget.hash.split('#')[1]
}
return mTabID
}
Finally, keep an eye on the corpus as you mix EventTarget
and EventTarget
in one of your examples.
source to share
You can use type protectors to implement this.
Example:
function isAnchor(eventTarget: EventTarget): eventTarget is HTMLAnchorElement {
return (<HTMLAnchorElement>eventTarget).hash != undefined;
}
function getTabID(eventTarget: EventTarget): string {
let mTabID: string
// Do the type assertion in the parameter
if (isAnchor(eventTarget)) {
mTabID = eventTarget.hash.split('#')[1]
} else {
mTabID = eventTarget.dataset.tabId
}
return mTabID
}
Note. I didn't know which dataset interface was part of, but you can also make a protection type for it.
You can read more about the types of guards in the guide here .
source to share