首页 > 解决方案 > TypeScript 中的 Cheerio `this` 对象使“TS2683:'this' 隐式具有类型'any',因为它没有类型注释。”

问题描述

我在 Typescript 项目中使用 Cheerio 来抓取HTML 页面。但我不明白如何解决这个问题:

TS2683: 'this' implicitly has type 'any' because it does not have a type annotation.

这是我的代码。任何想法 ?

import * as cheerioReq from 'cheerio-req';

async function crawl (options) {
    await cheerioReq({ url: options.url, headers: options.headers }, (err, $: CheerioStatic) => {
        if(err) console.log(err);

        $('.title').each((i, elem) => {
            console.log(i, elem, $(this).text().trim());
        })
    })

}

crawl(options);

标签: typescriptcheerio

解决方案


您可以使用常规函数解决此问题。

首先使用: 在终端中安装 Cheerio 类型 npm i @types/cheerio,然后导入 Cheerio import cheerio from 'cheerio';:。

现在更改您的代码,使其如下所示:

  $('.title').each(function(this: CheerioElement, i, elem) {
    console.log(i, elem, $(this).text().trim());
  })

顺便说一句, this 和 elem 在这种情况下是相同的。


推荐阅读