daniel
daniel

Reputation: 148

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?

Upvotes: 0

Views: 4221

Answers (1)

random
random

Reputation: 7891

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

Upvotes: 1

Related Questions