以下是borisyankov/DefinitelyTypedD3.Layout.GraphNode
中定义的和D3.Layout.GraphLink
的定义。
export interface GraphNode {
id: number;
index: number;
name: string;
px: number;
py: number;
size: number;
weight: number;
x: number;
y: number;
subindex: number;
startAngle: number;
endAngle: number;
value: number;
fixed: bool;
children: GraphNode[];
_children: GraphNode[];
parent: GraphNode;
depth: number;
}
export interface GraphLink {
source: GraphNode;
target: GraphNode;
}
但是,aGraphNode
不一定总是具有所有这些属性。例如,这里是 aGraphLink
和source:GraphNode
a target:GraphNode
,两者都不具备所有属性。
此外,我不能有这样的课程:
class GraphData {
nodes: D3.Layout.GraphNode[];
links: D3.Layout.GraphLink[];
}
因为这样做是行不通的:
var data:GraphData = {
"nodes": [{
"group": 0,
"id": 0
}, {
"group": 0,
"id": 1
}, {
"group": 0,
"id": 2
}],
"links": [{
"source": 0,
"target": 2,
"value": 1
}, {
"source": 0,
"target": 0,
"value": 1
}, {
"source": 2,
"target": 1,
"value": 1
}, {
"source": 2,
"target": 1,
"value": 1
}]
}
打字稿编译器给了我这个错误:
Compile Error.
See error list for details
C:/Projects/MyGraph/app.ts(111,23): error TS2082: Supplied parameters do not match any signature of call target:
Types of property 'nodes' of types '{ "nodes": { "group": number; "id": number; }[]; "links": { "source": number; "target": number; "value": number; }[]; }' and 'GraphData' are incompatible:
Type '{ "group": number; "id": number; }' is missing property 'index' from type 'D3.Layout.GraphNode'.
解决此问题的一种方法是使界面中的所有字段都是GraphNode
可选的。但是这样界面就没用了。在这种情况下,如何利用 TypeScripts 静态类型?