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[]) {
//...
}
}