Created
January 4, 2022 10:07
-
-
Save PabloLION/7987776521b08c89872c460eee1055da to your computer and use it in GitHub Desktop.
`array.push` will not trigger "set" method of proxy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Run it on TS Playground