0

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?

1 Answer 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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.