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
3.9k views
in Technique[技术] by (71.8m points)

TypeScript 参数变成 never 类型

  add(data:any, toData:any, traversal:Function) {
    let child = new Node(data),
      parent :null |Node =null,
      callback = function(node:Node) {
        if (node.data === toData) {
          parent = node
        }
      };
    this.contains(callback, traversal)

    if (parent) {
      parent.children.push(child)
      child.parent = parent
    } else {
      throw new Error('Cannot add node to non-existent parent')
    }
  }

这是一个类中的函数在 parent.children.push(child)中报了
image.png

其中的在if (parent) {这一句中 parent 被断言成了null 而失去了我定义的 null | Node 中的 Node
我之前的callback 函数明明给它作了一个赋值,这里却变成了 null

导致我后面的 parent 断言变成 never

image.png

求解


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

1 Answer

0 votes
by (71.8m points)
parent!.children.push(child)

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

...