简体   繁体   中英

how to handle typescript error for type of string on query

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" 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" .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM