Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 对象破坏导致';绝不';键入打字脚本_Typescript_Types_Object Destructuring - Fatal编程技术网

Typescript 对象破坏导致';绝不';键入打字脚本

Typescript 对象破坏导致';绝不';键入打字脚本,typescript,types,object-destructuring,Typescript,Types,Object Destructuring,我的代码如下: 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); } expor

我的代码如下:

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)) });
                                          ~~~~~
我似乎不明白为什么这是自动推断“从不”类型。我尝试显式地声明类型,但没有成功。

为这个问题提供了一些线索:

这是由
strict
noImplicitAny:false
组合造成的。一般来说,如果
strict
处于启用状态,则
noImplicitAny
也处于启用状态;这组特定的设置将暴露一些奇怪的行为。如果同时启用这两个选项,则会看到一个错误,即
[]
隐式地
任何[]
;如果两者都关闭;我们将使用控制流分析,并在推(1)之后将数组视为一个
number[]

设置的特定组合(
“strict”:true,“noImplicitAny”:false,
)意味着我们不允许自己使用控制流分析或允许数组隐式地
任何[]
,因此
从不[]
是唯一允许的选项

如果您不打算启用
noImplicitAny
,我建议您关闭
strict

因此,这可能是一个可行的解决办法

export function testGraph({id=0,name=“test”,nodes=[]作为数组}):Graph{
...

节点=[]
。什么数组

[]
永远不足以让typescript推断数组类型,在这种特殊情况下,它被推断为
从不[]
。因此,通常,您只需为整个解构对象提供一个类型,并包括适当的数组类型:

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> {
    //...
}
class Graph<T> {
    constructor(id: number, name: string, nodes: T[]) {
        //...
    }
}