属性 'attribs' 在类型 'Element' 上不存在 [cheerio]

Property 'attribs' does not exist on type 'Element' [cheerio]

我收到错误 Property 'attribs' does not exist on type 'Element' 而 运行 代码。我不确定为什么会抛出此错误。我查看了cheerio的类型定义,发现attribsTagElement的属性。我不确定如何修复它,因为它会自动为 element 选择类型 Element。我是打字稿的新手,所以也许我犯了一个新手错误。

const $ = cheerio.load(response.body),
    selection = $('td:nth-child(1) .spaceit_pad'),
    filteredNodes = [];

selection.toArray().map((element) => {
    const attr = element.attribs;
    if (attr.class.split(' ').length === 1) {
        filteredNodes.push(element);
        console.log(typeof element);
    }
});

您可以尝试使用类型保护来检查它是否是您在选择中找到的标签元素:

const isTagElement = (element: any): element is cheerio.TagElement => {
  return element?.attribs !== undefined;
};

selection.toArray().map((element: cheerio.Element) => {
  if (isTagElement(element)) {
    const attr = element.attribs;
    if (attr.class.split(" ").length === 1) {
      filteredNodes.push(element);
      console.log(typeof element);
    }
  }
});