Search code examples
arraystypescripttypeerrorcheerio

Getting the error: Argument of type {JSON Object} is not assignable to the parameter of 'never'


I'm trying to do some web scraping using typescript, axios and cheerio but I'm running into issues with this error:

Argument of type '{ contestcode: string; contestname: string; conteststart: string; contestduration: string; startsin: string; }' is not assignable to parameter of type 'never'.

this is my code

//function for data scraping
async function datascraper(){
    //try catch block
    try{
        //getting the url from axios
        const {data} = await axios.get(url);
        //loading the html using cheerio load
        const $ = load(data);
        //defining the target class
        const contests = $('.MuiTableBody-root',$.html());
        //array to fit in the json objects
        const contestlist = [];
        contests.each((idx,el)=>{
            //creating an object
        const contestdetails = {contestcode: '',
                                contestname: '',
                                conteststart: '',
                                contestduration: '',
                                startsin:''}

        contestdetails.contestcode = $(el).children('p').text();

        //error: Argument of type '{ contestcode: string; contestname: string; conteststart: string; contestduration: string; startsin: string; }' is not assignable to parameter of type 'never'.
        contestlist.push(contestdetails);
    });

    console.dir(contestlist);
    
}
catch(err){
    console.log(err);

}
}

I'm getting the error at contestlist.push(contestdetails) line

I've tried trouble shooting it by creating an interface and defining the array as a string[] but nothing is working and I ran out of ideas. I keep getting the same error.


Solution

  • When you instantiate an array without explicitly typing it (and the array itself doesn't contain any type information), TypeScript defaults to typing that array as never[]

    const contestlist = ['someString']; // string[]
    const contestlist = [123];          // number[]
    const contestlist = [];             // never[]
    

    If you intend to push a value of a given type to this array later on, explicitly typing the array will avoid this inference path

    type ContestDetails = {
      contestcode: string;
      contestname: string;
      conteststart: string;
      contestduration: string;
      startsin: string;
    }
    
    const contestlist: ContestDetails[] = [] // ContestDetails[]
    const contestdetails: ContestDetails = {
      contestcode: '',
      contestname: '',
      conteststart: '',
      contestduration: '',
      startsin: ''
    }
    
    contestList.push(contestdetails)  //valid