reactjs - Typescript:类型文字中的计算属性名称必须引用其类型为文字类型或“唯一符号”类型的表达式。ts(1170)
问题描述
我正在尝试动态生成网格的列。(反应数据表组件)。
下面是如何定义列的示例。
const columns = [
{
name: 'Title',
selector: (row: { title: any; }) => row.title,
},
{
name: 'Year',
selector: (row: { year: any; }) => row.year,
},];
我想从一个数组( API Fetch )动态地做同样的事情。
const data = ["Title", "Year"];
const columns = data.map((element) => ({
name: element.toLowerCase(),
selector: (row: { [element.toLowerCase()]: any; }) => row[element],
}));
console.log(columns)
这段代码不起作用,我一直有这个错误:
[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)
行[元素] =>
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)
解决方案
您的data
数组是string[]
此代码中的类型。如果您想将该数组的元素用作类型,则必须对它进行类型转换,as const
以便值是文字类型而不是string
.
const data = ["Title", "Year"] as const;
完整示例:
const data = ["Title", "Year"] as const;
const columns = data.map((element) => ({
name: element.toLowerCase(),
selector: (row: { [key in typeof element]: any; }) => row[element],
}));