typescript - 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);
解决方案
您可以使用常规函数解决此问题。
首先使用: 在终端中安装 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 在这种情况下是相同的。
推荐阅读
- java - 为什么我们不能在java的类构造函数中声明变量?
- javascript - 如何匹配对象的某些属性或数组的某些元素
- reactjs - 如何使用 JEST 测试子组件中的条件文本?
- django - 从 DRF API 工具调用时,Django Rest Framework 视图不起作用
- javascript - 我有一个 AutoSave 组件在反应,我将如何检查 saveData 道具与以前的状态,这样我只抓住新的 val
- node.js - 如何在不破坏打字稿的情况下将 CommonJS 库导入 ES 模块项目?
- python - sqlite3 OperationalError:没有这样的表:repl.it 上的主要错误,但 PC 上没有
- c# - 事件是数据还是行为?
- python - 应用 lambda 根据列值 pandas 的长度更改列
- sql - 在sql sql Oracle中创建表后如何使用约束