类型描述错误 对象可能是 "未定义的"。

问题描述 投票:-2回答:1

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

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())
    }

为什么会出现这个错误?

typescript
1个回答
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 ?
    }
© www.soinside.com 2019 - 2024. All rights reserved.