[英]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):我有一个遍历tmpNav
数组并显示数据的循环,其中有时我使用tmpNav
中的类型插入基于它的 class(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: header.nodeName
会引发类型错误,因为它返回一个与类型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.用string
添加它会导致我的classes[type]
抛出错误,因为它无法匹配该类型。
I'm unsure how to go about this.我不确定如何 go 关于这个。 I always know that the array will puch one of the type with header.nodeName
as it's just a querySelector
for "h2, h3"
.我一直都知道该数组将使用header.nodeName
提供一种类型,因为它只是"h2, h3"
的querySelector
。
A more suitable solution is using a conditional value check to narrow type of header.nodeName
更合适的解决方案是使用条件值检查来缩小header.nodeName
的类型
if (header.nodeName === 'H3' || header.nodeName === 'H2') {
tmpNav.push(...);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.