Home > Blockchain >  Typescript : A computed property name in a type literal must refer to an expression whose type is a
Typescript : A computed property name in a type literal must refer to an expression whose type is a

Time:10-23

I'm trying to dynamically generate the columns of a grid. ( react-data-table-component ).

Here is an example of how to define the column.

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

I would like to do the same dynamically from an Array ( API Fetch ).

    const data = ["Title", "Year"];
    const columns = data.map((element) => ({
      name: element.toLowerCase(),
      selector: (row: { [element.toLowerCase()]: any; }) => row[element],
    }));
    
    console.log(columns)

This code does not work, I keep having this error :

[element.toLowerCase()] =>

A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type.ts(1170)

row[element] =>

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'. No index signature with a parameter of type 'string' was found on type '{}'.ts(7053)

CodePudding user response:

Your data array is type of string[] in this code. If you want to use the elements of that array as types, you must type cast it with as const so that the values are literal types instead of string.

const data = ["Title", "Year"] as const;

Full example:

const data = ["Title", "Year"] as const;
const columns = data.map((element) => ({
  name: element.toLowerCase(),
  selector: (row: { [key in typeof element]: any; }) => row[element],
}));
  • Related