Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript extend object in module

What I want to do is really similar to this and this except I'm trying to figure out how to put an ArrayExtension inside a module.

I'm trying to get something similar to the way C# extension methods work, that way I can just import the module and I'll have my extra methods. The links I provided show how to extend an existing object, but I haven't been able to figure out how to encapsulate that into a module.

like image 753
PrettyFlower Avatar asked Nov 23 '25 01:11

PrettyFlower


1 Answers

If you're targeting non-browser environments like node.js this will be possible because you will be able to pass references to your module's global members, such as Array, to other modules. Those other modules can then extend the passed in object and/or its prototype with extra functionality which will be only accessible by the calling module. Other modules would have to do the same in order to get these extensions; therefore, conflicts are minimized since imports are explicit.

However, in browser environments this is not the case since there is only one window object and any changes to its members are available everywhere. As soon as any of your modules extended Array those extensions would be available to all other modules -- increasing the possibility for conflicts and making the code harder to reason about.

With that said, there are patterns in JS, and therefore TypeScript, which should accomplish what you want. One such pattern is the 'mixin' pattern which allows you to add on extra functionality on an object instance basis. You could separate re-usable code into mixin modules which could then be applied to an object when needed, or even automatically in constructors. Take a look at this for a decent overview and implementation examples: http://javascriptweblog.wordpress.com/2011/05/31/a-fresh-look-at-javascript-mixins/

like image 172
nxn Avatar answered Nov 26 '25 12:11

nxn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!