Drakinite
Drakinite

Reputation: 362

Is there a way in TypeScript to use element.hasAttribute() as a check without dummy variables?

In JS, I believe it is common to do the following to retrieve an element's attribute:

let myAttr;
if (myElem.hasAttribute('my-attribute')) {
  myAttr = myElem.getAttribute('my-attribute');
}

However, due to TS only noticing that hasAttribute returns a boolean and getAttribute returns string | null, it doesn't realize that myElem.hasAttribute('my-attribute') is enough checking to guarantee that myElem.getAttribute('my-attribute') will return a string.

Is there a way to do this kind of check in TS, in a way that doesn't require dummy variables (or get out of hand in the case of multiple attribute checks) like the following?

let myAttr: string;
let myAttr1 = myElem.getAttribute('my-attribute');
let myAttr2 = myElem.getAttribute('my-attribute-2');
if (typeof myAttr1 === 'string') myAttr = myAttr1;
else if (typeof myAttr2 === 'string') myAttr = myAttr2;

Upvotes: 0

Views: 779

Answers (0)

Related Questions