'Cheerio `this` object in TypeScript make "TS2683: 'this' implicitly has type 'any' because it does not have a type annotation."

I'm using Cheerio in a Typescript project to scrape a HTML page. But I don't understand how to solve the issue :

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

Here is my code. Any idea ?

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


Solution 1:[1]

You can solve this using a regular function.

  1. First install Cheerio types in the terminal: npm i @types/cheerio

  2. Next import Cheerio: import cheerio from 'cheerio';

  3. Finally change your code so that it looks as follows:

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

** this and elem are the same in this context.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1