Typescript在闭包中看不到参数验证

Typescript在闭包中看不到参数验证,typescript,Typescript,在我的代码中 interface INode { id: number, label: string; parentId?: number; } let nodes: null | INode[] = null; nodes = [ { id: 0, label: 'zero' }, { id: 1, label: 'one', parentId: 0 }, { id: 2, label: 'two', parentId: 0 },

在我的代码中

interface INode {
    id: number,
    label: string;
    parentId?: number; 
}

let nodes: null | INode[] = null;

nodes = [
    { id: 0, label: 'zero' },
    { id: 1, label: 'one', parentId: 0 },
    { id: 2, label: 'two', parentId: 0 },
    { id: 3, label: 'three', parentId: 1 },
    { id: 4, label: 'four', parentId: 3 },
]


function calcBreadcrumbs(nodes: null | INode[]) {
  if (nodes === null) return;

  const id = 33

  function _findNode(nodeId: number): void {
    const node: INode | undefined = nodes.find(n => n.id === id);
    if (node === undefined) {
      throw new Error(`calcBreadcrumbs. Node ${nodeId} not found`);
    }

    // some code

    if (node.parentId) _findNode(node.parentId);

    return;
  }

  _findNode(id);
}
如果节点===null,则检查
。但是TS talk me'对象可能是'null'。(2531)'
如果您将节点传递给_findNode函数,则TS不起作用

function _findNode(nodes: INode[], nodeId: number): void {...}

为什么会这样?如何解决此问题?

这是因为在第一个示例中,内部函数的
节点类型仍然是
null | INode[]
,并且可能是
null
。例如,可以在调用
\u findNode(id)之前将其设置为
null

可能的解决方案之一是将参数分配给另一个变量:

function calcBreadcrumbs(nodes: null | INode[]) {
  if (nodes === null) return;

  const guardedNodes = nodes; // guardedNodes is INode[]
  const id = 33

  function _findNode(nodeId: number): void {
    const node: INode | undefined = guardedNodes.find(n => n.id === id);
    // ...

    return;
  }

  _findNode(id);
}


另一种选择是使用:


操作
x
生成一个
x
类型的值,其中
null
undefined
被排除在外。仅当您完全确定该值已定义时才使用此选项。

this^。更多关于TS为何如此设计的信息,请参见此处
function calcBreadcrumbs(nodes: null | INode[]) {
  if (nodes === null) return;

  const id = 33

  function _findNode(nodeId: number): void {
    const node: INode | undefined = nodes!.find(n => n.id === id);
    // ...

    return;
  }

  _findNode(id);
}