【问题标题】:Property 'attr' does not exist on type 'CheerioElement'“CheerioElement”类型上不存在属性“attr”
【发布时间】:2020-04-07 14:10:13
【问题描述】:

为什么 TypeScript 会警告 Property 'attr' does not exist on type 'CheerioElement'

async function inlineImages(serializedSvg: string) {
  const $ = cheerio.load(serializedSvg);

  await Promise.all(
    Array.from($('image[href^="http"]')).map(async (el: CheerioElement) => {
      const url = el.attr("href"); // <--- HERE
      if (!url) {
        return;
      }

      const data = await requestBase64(url);
      if (!data) {
        return;
      }
      el.attr("href", data); // <--- AND HERE
    })
  );

  return serializedSvg;
}

【问题讨论】:

    标签: typescript cheerio


    【解决方案1】:

    它给出这个警告是因为'CheerioElement' 的输入方式,它没有'attr' 属性。

    interface CheerioElement {
        // Document References
        // Node Console
        tagName: string;
        type: string;
        name: string;
        attribs: { [attr: string]: string };
        children: CheerioElement[];
        childNodes: CheerioElement[];
        lastChild: CheerioElement;
        firstChild: CheerioElement;
        next: CheerioElement;
        nextSibling: CheerioElement;
        prev: CheerioElement;
        previousSibling: CheerioElement;
        parent: CheerioElement;
        parentNode: CheerioElement;
        nodeValue: string;
        data?: string;
        startIndex?: number;
    }
    

    参考可用的类型:https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/cheerio/index.d.ts

    'attr' 是 'Cheerio' 类型的属性,这是调用 'CheerioStatic' $() 返回的内容

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-09
      • 2021-07-10
      • 2017-07-22
      • 2023-03-26
      • 2023-04-02
      • 2019-12-20
      • 2021-12-07
      相关资源
      最近更新 更多