1

我的代码如下:

export function testGraph({ id = 0, name = "test", nodes = [] }): Graph {
  if (nodes.length === 0) {
    const dummyNode = testNode({});
    return new Graph(id, name, [dummyNode]);
  }

  return new Graph(id, name, nodes);
}
export function testDatabase({ id = 0, name = "test", graphs = [] }): Database {
  if (graphs.length === 0) {
    const dummyGraph = testGraph({ nodes: new Array(new Node(0)) });
    return new Database(id, name, [dummyGraph]);
  }

  return new Database(id, name, graphs);
}

但这给了我以下错误:

Type 'Node[]' is not assignable to type 'never[]'.
      Type 'Node' is not assignable to type 'never'.

    40     const dummyGraph = testGraph({ nodes: new Array(new Node(0)) });
                                          ~~~~~

我似乎无法理解为什么这会自动推断“从不”类型。我尝试明确声明类型但没有运气。

4

2 回答 2

1

这个关于 Github 的讨论对这个问题有一些启发:

这是由 和 的组合引起strictnoImplicitAny: false。一般来说,我们期望 ifstrict开启,noImplicitAny也开启;这组特定的设置会暴露一些奇怪的行为。如果您同时使用两者,您会看到有关存在的错误[]隐含any[];如果两者都关闭;我们将使用控制流分析并将数组视为number[]push(1); 之后的a。

设置的特定组合 ( "strict": true, "noImplicitAny": false,) 意味着我们不允许自己使用控制流分析或允许数组是隐式的any[],因此never[]是唯一剩下的允许选项。

strict如果你不打算打开,我建议关闭noImplicitAny

所以,这可能是一个可能的出路

export function testGraph({ id = 0, name = "test", nodes = [] as Array<Node> }): Graph {
...

于 2021-01-06T18:26:41.053 回答
1

nodes = []. 什么数组?

[]打字稿永远不足以推断出数组类型,并且never[]在这种特殊情况下被推断出来。因此,通常,您只需为整个解构对象提供一个类型,并包含正确的数组类型:

export function testGraph({
    id = 0,
    name = "test",
    nodes = []
}: {
    id?: number,
    name?: string,
    nodes?: Node[]
}): Graph {
    //...
}

或者使用泛型从调用者推断。

export function testGraph<T>({
    id = 0,
    name = "test",
    nodes = []
}: {
    id?: number,
    name?: string,
    nodes?: T[]
}): Graph<T> {
    //...
}

请注意,您可能还想要Graph通用,以便您传递给的节点类型testGraph也可以反映在Graph的节点中。

这可能看起来像:

class Graph<T> {
    constructor(id: number, name: string, nodes: T[]) {
        //...
    }
}
于 2021-01-06T18:32:19.617 回答