Skip to content

Instantly share code, notes, and snippets.

@PabloLION
Created January 4, 2022 10:07
Show Gist options
  • Save PabloLION/7987776521b08c89872c460eee1055da to your computer and use it in GitHub Desktop.
Save PabloLION/7987776521b08c89872c460eee1055da to your computer and use it in GitHub Desktop.
`array.push` will not trigger "set" method of proxy
/* This example is to show that
* array.push will not trigger "set" method of proxy
* because array is mutable.
*/
interface MyObj {
arr: number[];
}
const myObj: MyObj = { arr: [] };
const oa = new Proxy(myObj, {
get(target, prop: keyof MyObj) {
const ar = target[prop];
if (Array.isArray(ar) && ar.length === 0) {
throw Error('empty array');
}
return ar;
},
set(target, prop: keyof MyObj, value) {
target[prop] = value;
console.log('pushed value : ', value); // DEV_LOG_TO_REMOVE
return true;
},
});
oa.arr.push(5);
oa.arr.push(2);
console.log('oa : ', oa); // DEV_LOG_TO_REMOVE
@PabloLION
Copy link
Author

PabloLION commented Jan 4, 2022

Run it on TS Playground

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment