首页 新闻 会员 周边 捐助

typescript 中如何将数组设置为 immutable

0
悬赏园豆:30 [已解决问题] 解决于 2025-08-04 14:39

这是在改进园子 vscode 插件时遇到的一个问题,下面的 PostCate 类型有个 children 属性,不知什么原因会造成 children 的值被置空,从而造成 tree view 的数据绑定出现问题

export class PostCateStore {
    constructor(private categories: PostCate[]) { }
}
export class PostCate {
     children?: PostCat[] | null
}

排查半天没找到根源,现在想把这个数组设置为 immutable 即只读状态,以避免数组元素的值被修改

dudu的主页 dudu | 高人七级 | 园豆:24853
提问于:2025-08-04 14:05
< >
分享
最佳答案
0

typescript 中有个现成的 ReadonlyArray

export class PostCateStore {
    constructor(private categories: ReadonlyArray<PostCate>) { }
}

改用 ReadonlyArray 之后,立马通过编译错误就发现了问题所在,是下面的代码中 const queue = this.categories 引起的问题

getChildren(categoryId: number) {
    if (this.isNullOrEmpty) return []

    let children: PostCate[] = []
    const queue = this.categories
    while (queue.length > 0) {
        const current = queue.pop()
        if (current == null) continue
        if (current.categoryId === categoryId) {
            if (current.children != null) children = current.children
            break
        }

        if (current.children != null) for (const child of current.children) queue.unshift(child)
    }

    children = PostCateeStore.clonePostCate(children)
    return children
}

改为调用 getRoots 方法从 this.categories clone 根节点解决了

const queue = this.getRoots()
dudu | 高人七级 |园豆:24853 | 2025-08-04 14:37
其他回答(1)
0

typescript有个Readonly关键字可以试试

type TItem = {
    name: string
    children?: Readonly<TItem[]>
}
收获园豆:30
彼时今日 | 园豆:690 (小虾三级) | 2025-08-04 14:27

还有readonly和ReadonlyArray,可以根据需求选择使用

支持(0) 反对(0) 彼时今日 | 园豆:690 (小虾三级) | 2025-08-04 14:32

@彼时今日: ReadonlyArray 是正解

支持(0) 反对(0) dudu | 园豆:24853 (高人七级) | 2025-08-04 14:39
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册