Skip to content

deepFreeze 深度冻结对象

function deepFreeze<T extends Record<string, any>>(obj: T): Readonly<T>

递归冻结对象及其嵌套对象,防止对象属性被修改。函数会返回被冻结后的同一个对象引用。

参数

参数名说明类型默认值
obj待冻结的对象T extends Record<string, any>必填

返回值

返回值说明类型
result深度冻结后的只读对象Readonly<T>

示例

typescript
import { deepFreeze } from '@mingto/tools'

const config = deepFreeze({
  theme: 'dark',
  nested: { enabled: true },
})

Object.isFrozen(config) // true
Object.isFrozen(config.nested) // true

注意事项

  • deepFreeze 会原地冻结传入对象,而不是创建新对象。
  • 冻结后再修改属性,在严格模式下会抛出错误。