【问题标题】:Cheerio `this` object in TypeScript make "TS2683: 'this' implicitly has type 'any' because it does not have a type annotation."TypeScript 中的 Cheerio `this` 对象使“TS2683:'this' 隐式具有类型'any',因为它没有类型注释。”
【发布时间】:2019-05-03 09:22:22
【问题描述】:

我在 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);

【问题讨论】:

  • 问题是您希望this 是谁?如果this 应该由cheerioReq 传递,请尝试使用常规函数而不是箭头函数

标签: typescript cheerio


【解决方案1】:

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

首先在终端中安装 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 在这种情况下是相同的。

【讨论】:

  • 这是cheerio.Element,而不是CheerioElement
  • 今天这行不通。 An arrow function cannot have a 'this' parameter.ts(2730)
猜你喜欢
  • 2017-06-16
  • 2021-09-27
  • 2019-08-04
  • 1970-01-01
  • 2018-10-29
  • 2020-09-25
  • 2020-03-06
  • 2020-12-17
  • 2019-12-21
相关资源
最近更新 更多