【发布时间】:2020-10-13 12:00:49
【问题描述】:
在我的代码中
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);
}
sandbox 1
我检查if nodes === null。但是 TS 告诉我'对象可能是'null'。(2531)'
如果将节点传递给 _findNode 函数,则 TS 不会发誓
function _findNode(nodes: INode[], nodeId: number): void {...}
sandbox 2 为什么会这样?如何解决这个问题?
【问题讨论】:
标签: typescript