1

以下是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不一定总是具有所有这些属性。例如,这里是 aGraphLinksource:GraphNodea target:GraphNode,两者都不具备所有属性。

D3.Layout.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 静态类型?

4

1 回答 1

1

所有这些都不是必需的,但也许有些是必需的,并且接口定义尚未反映这一点。也许您可以标记哪些是可选的以获取社区支持。

任何状况之下。当您想对他人实施严格的行为,但又想灵活地突破自我时,您可以使用任何。例如:

var data:GraphData = <any>{
    "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
    }]
}
于 2013-07-08T03:06:45.297 回答