typescript - 属性 'tagName' 在 ChildNode [Typescript] 类型上不存在

标签 typescript

我正在从父节点遍历 childNodes。我想访问子节点的 tagName,但错误是类型 ChildNode 上不存在 tagName。

const contentParsed = new DOMParser().parseFromString(content, 'text/xml');
const svgBody = contentParsed.querySelector('svg');

if (svgBody === null) throw new Error('content must be svg');
svgBody.childNodes.forEach((node) => node.tagName) // Property 'tagName' does not exist on type 'ChildNode'.ts(2339)

它适用于 javascript

const svgStr = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><title></title><path d="M 2.6846088,10.906645 H 28.979394 v 8.389403 H 15.580319 l -0.719092,1.438183 -3.811186,0.143819 -0.575273,-1.582002 H 2.6846088 Z" fill="#fff"/><path d="M2,10.555H30v9.335H16v1.556H9.778V19.889H2Zm1.556,7.779H6.667V13.666H8.222v4.667H9.778V12.111H3.556Zm7.778-6.223v7.779h3.111V18.334h3.111V12.111Zm3.111,1.556H16v3.112H14.444Zm4.667-1.556v6.223h3.111V13.666h1.556v4.667h1.556V13.666h1.556v4.667h1.556V12.111Z" fill="#cb3837"/></svg>`
const contentParsed = new DOMParser().parseFromString(svgStr, 'text/xml');
const svgBody = contentParsed.querySelector('svg');

if (svgBody === null) throw new Error('content must be svg');
svgBody.childNodes.forEach(node => console.log(node.tagName))

最佳答案

childNodes可以包含 non-element nodes , 使用 children 反而。

它在 JavaScript 中有效,因为 JS 不是类型安全的,并且您的父节点碰巧只有元素作为子节点(或者它打印了 undefined )。

关于typescript - 属性 'tagName' 在 ChildNode [Typescript] 类型上不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58742561/

相关文章:

typescript - 使用 TypeScript 3 项目引用时出现 "Cannot find module"错误

javascript - 如何动态地将组件传递给父组件

javascript - 通过 Angular 2/Ionic 2 中的构造函数刷新数据

typescript - 引用我的 TypeScript 模块时出错 TS2307 : Cannot find module

javascript - 可使用(或不带)_references.ts 自动解析和排序 TypeScript 依赖项的工具?

eclipse - 用于 eclipse 的免费 Typescript 插件?

visual-studio - Visual Studio 调试器获取数据提示

angular - ng6 : Dynamically form Variable names in html

typescript 基于接口(interface)从另一个对象创建一个对象

javascript - 是否可以在 TypeScript 注释中组合多种类型的成员?