typescript 声明类型报错never

代码片段如下:

init (name: string) {
    
    let chooseNode: INavNode | null = null;

    this.trv(this.data, function (item: INavNode) {
      if (item.name === name) {
        chooseNode = item;
      }
    });
    if (chooseNode) {
      this.selectedKeys2.value = [chooseNode.nodeid];
      if (chooseNode.parent.length === 3) {
        this.openKey1.value = [chooseNode.parent[1]]
        this.openKey2.value = [chooseNode.parent[2]]
      }
      if (chooseNode.parent.length === 2) {
        this.openKey1.value = [chooseNode.parent[1]]
      }
    }
  }

疑问:前面已经声明chooseNode是INavNode,所有chooseNode.xxxx下划线部分都在报错Property 'xxxx' does not exist on type 'never'

image.png

更新

报错原因:已声明类别的chooseNode: INavNode识别为never

更深层原因:不知,this.trv函数似乎打断了一切(这个函数只是做了一次树的深度优先遍历),可能是因为里面重新赋值了,具体什么原因不清楚

解决:

  1. 重新弄了个变量再声明下
  2. 如选中答案改下下结构
阅读 2.1k
1 个回答

换个结构看看,类型推测也不是万能的。

init (name: string) {
    
    const fn = (chooseNode: INavNode) => {
      this.selectedKeys2.value = [chooseNode.nodeid];
      if (chooseNode.parent.length === 3) {
        this.openKey1.value = [chooseNode.parent[1]]
        this.openKey2.value = [chooseNode.parent[2]]
      }
      if (chooseNode.parent.length === 2) {
        this.openKey1 = [chooseNode.parent[1]]
      }
    };

    this.trv(this.data, function (item: INavNode) {
      if (item.name === name) {
        fn(item);
      }
    });
  }

如果fn的声明里面还报错,那你还是检查一下INavNode到底是什么类型吧。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进