skip to Main Content

I am seeing the TypeScript error 'Parameter 'row' implicitly has an 'any' type' in my React datatable component, which occur when I declare this code in column selector, value row is highlighted with red.

Parameter 'row' implicitly has an 'any' type.
     8 |         {
     9 |             name: 'Year',
  > 10 |             selector: row => row.year,
       |                       ^^^
    11 |         },
    12 |     ];

This is the code

const columns = [
        {
            name: 'Title',
            selector: row => row.title,
        },
        {
            name: 'Year',
            selector: row => row.year,
        },
    ]; 

I am a newbie in react. Any help will be appreciated 🙂

2

Answers


  1. Chosen as BEST ANSWER

    After searching about implicity has an 'any' type I got the answer and this is the example code.

    const columns = [
        {
            name: 'Title',
            selector: (row:any) => row.title
        },
        {
            name: 'Year',
            selector: (row:any) => row.year
        },
    ];
    

    That's it, just put row inside parenthesis and add value of any. :)


  2. You’re not telling typescript where you’re going to be using columns so it implicitly things that row is any

    You could do something like this

    const buildColumns = <T extends Record<string, unknown>>(
      columns: { name: string; selector: (row: T) => string }[]
    ) => {
      return columns;
    };
    
    buildColumns<{ title: string; body: string }>([
      { name: "Title", selector: (row) => row.title },
      { name: "Body", selector: (row) => row.body },
      //                          ^? (parameter) row: { title: string; body: string; }
    
      { name: "Prop missing", selector: (row) => row.propMissing },
    ]);
    

    It’s essentially a wrapper function for helping you type rows (you could also make it a prop so you can directly pass columns as a prop to the datatable)

    Also if you don’t have an explicit type declaration for your row you can do buildColumns<typeof rows[number]>

    • typeof row -> gets the type of the array
    • typeof row[number] -> gets the type of a single element of the array
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search