Function: objReadOnly()
objReadOnly<
T,Revocable,Result>(obj,config?):Result
Defined in: packages/core/src/obj/objReadOnly.ts:75
Constructs a read-only proxy of an object. Prevents modification or deletion of existing properties based on configuration.
Applies only to top-level properties.
Type Parameters
T
T extends object | unknown[]
Revocable
Revocable extends boolean = false
Result
Result = Revocable extends true ? object : T
Parameters
obj
T
input object
config?
ObjReadOnlyConfig<T, Revocable>
(optional) extra configuration
Returns
Result
Readonly object or object containing readonly object and revoke function
Examples
Create a readonly object and silently ignore any attempt of property add, update and delete operations
import { objReadOnly } from '@superutils/core'
const obj = objReadOnly({ a: 1, b: 2})
obj.a = 3
delete obj.a
console.log(obj.a) // 1
obj.c = 4
console.log(obj.c) // undefinedCreate a readonly object and throw error on any attempt of property add, update and delete operations
import { fallbackIfFails, objReadOnly } from '@superutils/core'
const obj = objReadOnly(
{ a: 1, b: 2},
{ silent: false }
)
try {
obj.a = 3
} catch(err) { console.log('update failed:', err.message) }
try {
delete obj.a
} catch(err) { console.log('delete failed:', err.message) }
try {
obj.c = 4
} catch(err) { console.log('add failed:', err.message) }
console.log(obj) // { a: 1, b: 2 }Create a readonly object and throw error on any attempt of property update and delete operations but allow adding new properties
import { fallbackIfFails, objReadOnly } from '@superutils/core'
const obj = objReadOnly(
{ a: 1, b: 2},
{
add: true,
silent: false
}
)
obj.c = 4
console.log(obj.c) // 4