简体   繁体   English

如何处理查询中字符串类型的 typescript 错误

[英]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.

相关问题 如何在 javascript / typescript 中处理单个项目和字符串类型的数组 - How to handle both a single item and an array of string type in javascript / typescript 如何处理`Type | typescript 和错误检查/测试中的布尔值返回值 - how to handle `Type | boolean` return values in typescript and error checking / tests 打字稿类型'字符串'不可分配给类型“错误 - Typescript Type ‘string’ is not assignable to type" error TypeScript 错误:类型“字符串”不可分配给排版类型 - TypeScript error: Type 'string' is not assignable to type for Typography 如何处理 Typescript 中的错误返回类型? - How do handle Error return types in Typescript? 如何在 Typescript 中处理 eventListeners 上的“Event”类型和“CustomEvent”类型 - How to handle 'Event' type and 'CustomEvent' type on eventListeners, in Typescript 输入'字符串| null' 不能分配给类型 'string | TypeScript 的未定义错误 - Type 'string | null' is not assignable to type 'string | undefined error with TypeScript 'string | 类型的参数 undefined' 不可分配给“string”类型的参数 - TypeScript 错误 - Argument of type 'string | undefined' is not assignable to parameter of type 'string' - TypeScript error 如何解决 typescript 错误在“对象”类型上找不到带有“字符串”类型参数的索引签名 - How do i solve typescript error No index signature with a parameter of type 'string' was found on type 'Object' TypeScript, object 类型为 bool 或 () => bool,如何处理? - TypeScript, object with prop of type bool or () => bool, How to handle?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM