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

Time:05-01

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?

CodePudding user response:

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);
}
  • Related