ts null类型报错,但我已经做了非空判断
代码如下:Playground Link
class TreeNode {
val: number
left: TreeNode | null
right: TreeNode | null
constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
this.val = (val === undefined ? 0 : val)
this.left = (left === undefined ? null : left)
this.right = (right === undefined ? null : right)
}
}
function preorderTraversal(root: TreeNode | null): number[] {
const result: number[] = []
read(root)
function read(node: typeof root): TreeNode[] {
if (root === null) return []
result.push(node.val)
if (node.left) read(node.left)
if (node.right) read(node.right)
}
return result
}
遇到的问题:
- 如图所示的报错,函数返回值可能为undefined
- 最开始做了null的判断,node还是会被判定为可能为null
现在代码在逻辑上没有问题,且在leetcode上也能顺利通过,而且,我认为目前的类型也是合理的。现在想把所有的报错全都解决掉,除了用!
做非空断言,还有别的什么方式吗?
转载自:https://segmentfault.com/a/1190000042486987