Skip to content

Instantly share code, notes, and snippets.

@gordonbrander
Created March 8, 2023 13:55
Show Gist options
  • Save gordonbrander/1f495be55db2a54554eebd3ab8c7a8a5 to your computer and use it in GitHub Desktop.
Save gordonbrander/1f495be55db2a54554eebd3ab8c7a8a5 to your computer and use it in GitHub Desktop.
Ready-only Proxy - a read-only view over JS objects
export const isObject = thing => thing != null && typeof thing === "object"
export class ReadOnlyProxyWriteError extends Error {}
const ReadOnlyProxyDescriptor = {
get: (target, key) => {
let value = target[key]
if (!isObject(value)) {
return value
}
return readonly(value)
},
set: (target, key) => {
throw new ReadOnlyProxyWriteError('Cannot write on read-only proxy')
},
deleteProperty: (target, key) => {
throw new ReadOnlyProxyWriteError('Cannot delete on read-only proxy')
}
}
// Create a read-only proxy over an object.
// Sub-properties that are objects also return read-only proxies.
export const readonly = obj => new Proxy(obj, ReadOnlyProxyDescriptor)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment