我有这样的类型..
type Table = {
fieldNames: {
id: string,
children?: string
},
rows: Array<(
Record<string, any> & {
label: string,
...
}
)>
};
所以,当我尝试创建基于这种类型的对象时......
const table: Table = {
fieldNames: {
id: "uuid",
children: "objects"
},
rows: [
{
label: "test"
}
]
};
没有错误,但我们已经声明了
fieldNames.id
和 fieldNames.children
它们必须在对象中,如何通过类型解决它?我已经尝试过typeof
和keyof
但没有结果:(
尝试创建包含标签并允许附加属性的行类型。
type Row = {
label: string;
[key: string]: any;
};
和 FieldNames 类型:这指定 id 和 Children 必须是 Row 类型的键。
type FieldNames = {
id: keyof Row;
children?: keyof Row;
};
然后创建结合 FieldNames 和 Row 对象数组的表类型。
type Table = {
fieldNames: FieldNames;
rows: Row[];
};
终于可以这样使用了
const table: Table = {
fieldNames: {
id: "id value",
children: "test text"
},
rows: [
{
label: "test",
field: "value"
}
]
};