简体   繁体   English

打字稿:类型文字中的计算属性名称必须引用类型为文字类型或“唯一符号”的表达式 type.ts(1170)

[英]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 ).我想从一个数组(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()] => [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.您的data数组是此代码中的string[]类型。 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 .如果您想将该数组的元素用作类型,则必须将其类型转换as const以便值是文字类型而不是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],
}));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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