简体   繁体   中英

Typescript : 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)

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)

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],
}));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM