'Typescript error: Type 'undefined' is not assignable to type 'string'

I've got the following function

this._list.addToFavs((<HTMLElement>event.currentTarget).dataset.code)

where addToFavs is defined as addtoFavs(currencyCode: string)

I'm getting the error "Type 'undefined' is not assignable to type 'string'" as dataset.code could in theory be 'undefined'. I know I can work around it by adding ! at the end, but I feel like it's kind of messy. I tried adding

if ((<HTMLElement>event.currentTarget).dataset.code == undefined) {
  throw Error('Code not set to details fav button')
}

but it doesn't stop the error. Is there any way around it besides defining currencyCode as string|undefined?



Solution 1:[1]

Before invoking the function, you can check the existence of specific data attribute.

const code = event.currentTarget?.dataset?.code;

if(code) {
    this._list.addToFavs(code);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 random