我有一个打字稿数据文件,供我的react组件使用。名为data.ts的Typescript数据文件具有以下数据项:
data.ts的内容
export default {
nodes: [
{ name: 'Myriel', group: 1 },
{ name: 'Napoleon', group: 1 },
{ name: 'Mlle.Baptistine', group: 1 },
],
links: [
{ source: 1, target: 0, value: 1 },
{ source: 2, target: 0, value: 8 },
{ source: 3, target: 0, value: 10 },
],
};
我正在将该数据从另一个组件main.tsx传递到反应组件(graph.tsx)。
main.tsx的相关内容
import data from "./data";
import Graph from "./Graph";
.
.
.
return <Graph width={width} height={height} data={data} />;
现在在Graph.tsx上,props接口定义如下:
interface IProps {
width: number;
height: number;
data: {
nodes: { name: string; group: number }[];
links: { source: number; target: number; value: number }[];
};
}
现在我想将数据更改为以下格式
在data2.ts
export default {
root : [
{name: "flare",
children: [{
name: "analytics",
children: [{
name: "cluster",
children: [{
name: "AgglomerativeCluster",
size: 3938
}, {
name: "CommunityStructure",
size: 3812
}, {
name: "HierarchicalCluster",
size: 6714
}, {
name: "MergeEdge",
size: 743
}]
}, {
name: "graph",
children: [{
name: "BetweennessCentrality",
size: 3534
}, {
name: "LinkDistance",
size: 5731
}, {
name: "MaxFlowMinCut",
size: 7840
}, {
name: "ShortestPaths",
size: 5914
}, {
name: "SpanningTree",
size: 3416
}]
}, {
name: "optimization",
children: [{
name: "AspectRatioBanker",
size: 7074
}]
}]
}
]
这就是Graph.tsx中的数据格式,就像这样。
data:{
root: {name:string, children: root}[];
};
根据较旧的数据格式(如下),将其写入IProps的正确格式是什么?
data: {
nodes: { name: string; group: number }[];
links: { source: number; target: number; value: number }[];
};
由于它是一个嵌套的数据链,如何在属性定义中对其进行定义?
答案 0 :(得分:0)
看起来数据的正确类型声明如下。定义此递归类型别名:
type MyNode = { name: string } & ({ children: MyNode[] } | { size: number });
然后使用:
data: { root: [MyNode] };