Reduce method declarations with JavaScript Proxy

Today I will show you how to reduce method declarations with JavaScript Proxy. As an example, I will use my own npm package “ts-checkers”. Via this package you can check any variables for specific values. Below you can see what methods the package has at the moment:

As you can see, methods above are presenting only one side of the possible cases, but you can use each of the methods for receiving the opposite result. Like, for example Is.Not.Null() will work, you can make the same with other methods in the package, if you are interested in how it works you can see the package here.
Or read the article with step by step instruction
The ts-checkers package is just an object with “check-only” methods for data which we can call via “Is”, for example:
Below is a declaration of a method which we used in the previous example:
As we can see, we have one declaration method for checking value, and we can call the method in both cases, and how is it possible? It is possible because we used JavaScript proxy for ”Methods”, each method returns a boolean result, the only thing we need to do is change the returned result to the opposite boolean value via prefix exclamation mark. I will show you, how it is possible to implement in TypeScript below:
Step #1 — Object “Methods”
All methods must be included in one object called “Methods”, and for future we will declare an interface “MethodsInterface”.

Step #2 — Object: “Is”
For the next step we need to export and initialise a new constant with the name “Is” which will have “Methods” with spread operator and the field “Not”:
Step #3 — JavaScript Proxy
For working JavaScript Proxy we need to set two arguments:
- target — is an object that we wrapped in a proxy.
- handler — is an object with methods that works like an interceptor.
An object with specific methods for the specific task can be added to the handler. We will use the apply function, because we want to change the result after calling the selected method. Since we want to declare “check-only” methods which will return only boolean values. We can change result to the opposite value via an exclamation mark:
Step #4 — Array of proxies
“Methods” is an object, and we cannot use the .map() method to change each method, for solving the problem, we can convert the object to an array and after that wrap each method in a JavaScript Proxy.
Step #5 — Object: “Not”
Now we convert our “arrayOfProxy” to an object and initialise a new constant “Not”.
Thank you for reading the article and if you have any comments or suggestions leave them here or create an issue in the repository.