Appearance
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会原地冻结传入对象,而不是创建新对象。- 冻结后再修改属性,在严格模式下会抛出错误。