打字稿错误对象可能是“未定义”

时间:2020-05-12 16:39:33

标签: typescript

我需要代码修复错误的帮助:

export class BSPTree {
    leaf: Box;
    lchild: undefined;
    rchild: undefined;

    constructor(leaf: Box){
        this.leaf = leaf;
    }


    getLeafs(){
        if (this.lchild === undefined && this.rchild === undefined)
            return [this.leaf]
        else
            return [].concat(this.lchild.getLeafs(), this.rchild.getLeafs())
    }

为什么会出现此错误?

1 个答案:

答案 0 :(得分:0)

您需要定义lchildrchild的类型,并在undefined时解决它们的情况。

export class BSPTree {
    leaf: Box;

    lchild: undefined | BSPTree; // <- here
    rchild: undefined | BSPTree; // <- here

    constructor(leaf: Box){
        this.leaf = leaf;
    }


    getLeafs(){
        if (this.lchild === undefined && this.rchild === undefined)
            return [this.leaf]
        else
            return [].concat(this.lchild?.getLeafs() || [], this.rchild?.getLeafs() || []) // <- here ?
    }