使用打字稿在 vis-network 中设置边的问题

Problem setting edges in vis-network with typescript

我正在关注来自 vis 的动态数据集示例,但当我尝试设置边缘时遇到打字稿错误。

我只有一个边缘数组,看起来像:

edgesArray = [
 { from: 1, to: 3 },
 { from: 1, to: 2 },
 { from: 2, to: 4 },
 { from: 3, to: 5 },
 ]

我将数据设置为

let data = {
  nodes: new vis.DataSet(nodesArray),
  edges: new vis.DataSet(edgesArray)
}

我得到的错误是在边缘。

No overload matches this call.
  Overload 1 of 2, '(options?: DataSetInitialOptions<"id">): DataSet<Partial<Record<"id", string | number>>, "id">', gave the following error.
    Type '{ from: number; to: number; } []' has no properties in common with type 'DataSetInitialOptions<"id">'.
  Overload 2 of 2, '(data: Partial<Record<"id", string | number>>[], options?: DataSetInitialOptions<"id">): DataSet<Partial<Record<"id", string | number>>, "id">', gave the following error.
    Argument of type '{ from: number; to: number; } []' is not assignable to parameter of type 'Partial<Record<"id", string | number>>[]'.

我使用的是 vis-network 5.2.4 版本。

这是标准的 TS 行为。您正在尝试将类型 A 分配给 B,但它们没有任何共同点。 DataSet 可以接受具有可选 ID 的项目。但是你的边没有 id,TS 只是说你做错了什么。

解决方法一:

import { Edge } from "vis-network";

const edgesArray: Edge[] = [
    { from: 1, to: 3 },
    { from: 1, to: 2 },
    { from: 2, to: 4 },
    { from: 3, to: 5 },
];

方案二:

const edgesArray = [
    { id: undefined, from: 1, to: 3 },
    { from: 1, to: 2 },
    { from: 2, to: 4 },
    { from: 3, to: 5 },
];

解决方案三:

const edgesArray: { id?: undefined, from: number, to: number }[] = [
    { from: 1, to: 3 },
    { from: 1, to: 2 },
    { from: 2, to: 4 },
    { from: 3, to: 5 },
];