0

I have a query that does something like this:

document.querySelectorAll("h2, h3").forEach(header => {
    tmpNav.push({name: header.textContent || header.innerHTML, id: header.id, type: header.nodeName});
})

The content that comes through is typed against this interface:

interface IContent {
    name: string,
    id: string,
    type: "H3" | "H2"
}

I have a loop that goes through the tmpNav array and display the data, in which at some point I use the type from the tmpNav to insert a class based on it (jss):

className={classes[type]}

The issue I'm facing is when I create this array, the type: header.nodeName throws a type error because it is return a string that does match the type type: "H3" | "H2"

Adding it with string will cause my classes[type] to throw an error as it can't match that type.

I'm unsure how to go about this. I always know that the array will puch one of the type with header.nodeName as it's just a querySelector for "h2, h3".

1 Answer 1

1

A more suitable solution is using a conditional value check to narrow type of header.nodeName

if (header.nodeName === 'H3' || header.nodeName === 'H2') {
  tmpNav.push(...);
}
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.