typescript - Typescript 接口不接受带有强制键的动态对象
问题描述
我需要为它作为道具传递的这个对象数组使用一个接口。
const playersData = [
{
id: 1, // Always a number (user always sends it)
extraNode: <ExampleComponent />, // If it's sent, it's React component (user may not send it)
// From here, we can receive anything because it depends on what
// the database sends. The type is always a string, but I can have
// many other values such as height, age, etc...
position: '1',
player: 'Miroslav Klose',
goals: '16',
games: '24',
country: 'Germany',
},
{
id: 2,
extraNode: <ExampleComponent />,
position: '2',
player: 'Ronaldo',
goals: '15',
games: '19',
country: 'Brazil',
},
];
id 将始终是一个数字,extraNode 将是一个 React 组件(如果它通过了)。问题是其他键值是动态的。这意味着它可以更多,例如年龄,身高等。
我试过这个,但它给了我一个错误:
export interface tableData {
id: number;
extraNode?: React.ReactNode;
[key: string]: string;
}
export interface TableProps extends HTMLAttributes<HTMLDivElement> {
tableData: tableData[];
}
解决方案
你可以使用一个Record
type Player = Record<string, string>
interface Data {
id: number;
extraNode: React.ReactNode;
player: Player;
}
const test:Data = {
id: 123,
extraNode: <Component />
player:{
position: "1",
player: "Miroslav Klose"
}
}
推荐阅读
- vue.js - 如何测试包含 v-text-field Vuetify 子组件的 vue 组件?
- jquery - 在 JQuery 自动完成填充输入字段后调用新函数
- python - 如何设置单个像素的颜色
- assembly - 在某些 MOV、XOR、RCL 和 DIV 指令之后查找寄存器值
- regex - 正则表达式文字的语法突出显示
- xml - Visual Studio LINQ for XML 子标签值的不同列表
- javascript - 单击从数组中获取值
- json - 如何使用 webpack 复制插件复制 json 文件并包含 package.json 文件中的版本?
- python - 从 cli 字符串输出中识别键和值的算法
- rust - 我在哪里可以找到 Rust 函数来从非均匀概率分布中获取值?