Typescript class wrapper

0xksure
2 min readMay 25, 2023

--

Ok, so I have been searching for a while for a Typescript pattern that allows me to do some operation before an object call. And I finally found it!

Photo by Caleb Gregory on Unsplash

Background

I’ve been staring a specific problem in the eyes for a long while, namely:

I want to wrap most or all methods from an external class with some logic

In my case I wanted to retry methods for a specific number of times.

Solution

It’s the Proxy object.

Let me show you something really cool

This is a working test file that demonstrate how you would wrap the ExternalModule class.

Now the real gotcha with using Proxy is knowing how methods and classes are called. First, the get is called to get the name of the method. The the method name is called. That’s why L21–39 is a bit confusing.

It is also useful to filter which calls you actually want to wrap, so on L25 I check the type of the calling object is actually a function. If it is something else then I just return the object on L38.

Conclusion

Hopefully, you found what you were searching for!

The Proxy object or pattern is pretty useful in order to reduce the amount of code in your projects. Please also note that if you just want to add custom logic to some of your internal methods you can use decorators.

Happy hacking!

--

--

0xksure
0xksure

Written by 0xksure

Developer and Mathematician

No responses yet