Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
219 views
in Technique[技术] by (71.8m points)

Object destructing resulting in 'never' type in TypeScript

My code is as follows:

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);
}

But this gives me the following error:

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)) });
                                          ~~~~~

I can't seem to understand why this is automatically inferring 'never' type. I tried explicitly declaring the type but to no luck.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This discussion on Github puts some light on the issue:

This is caused by the combination of strict and noImplicitAny: false. In general we expect that if strict is on, noImplicitAny is also on; this particular set of settings will expose some odd behavior. If you had both on, you'd see an error about the [] being implicitly any[]; if both were off; we'd use control flow analysis and treat the array as a number[] after the push(1);.

The particular combination ( "strict": true, "noImplicitAny": false, ) of settings means that we don't allow ourselves to use control flow analysis or allow the array to be implicitly any[], so never[] is the only remaining allowable option.

I'd recommend turning off strict if you're not going to have noImplicitAny on.

So, this may be a possible way out

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...