source: node_modules/ts-mixer/README.md

main
Last change on this file was d24f17c, checked in by Aleksandar Panovski <apano77@…>, 15 months ago

Initial commit

  • Property mode set to 100644
File size: 12.4 KB
RevLine 
[d24f17c]1# ts-mixer
2[version-badge]: https://badgen.net/npm/v/ts-mixer
3[version-link]: https://npmjs.com/package/ts-mixer
4[build-link]: https://github.com/tannerntannern/ts-mixer/actions
5[ts-versions]: https://badgen.net/badge/icon/4.2,4.4,4.6,4.8?icon=typescript&label&list=|
6[node-versions]: https://badgen.net/badge/node/12%2C14%2C16%2C18/blue/?list=|
7[![npm version][version-badge]][version-link]
8[![TS Versions][ts-versions]][build-link]
9[![Node.js Versions][node-versions]][build-link]
10[![Minified Size](https://badgen.net/bundlephobia/min/ts-mixer)](https://bundlephobia.com/result?p=ts-mixer)
11[![Conventional Commits](https://badgen.net/badge/conventional%20commits/1.0.0/yellow)](https://conventionalcommits.org)
12
13## Overview
14`ts-mixer` brings mixins to TypeScript. "Mixins" to `ts-mixer` are just classes, so you already know how to write them, and you can probably mix classes from your favorite library without trouble.
15
16The mixin problem is more nuanced than it appears. I've seen countless code snippets that work for certain situations, but fail in others. `ts-mixer` tries to take the best from all these solutions while accounting for the situations you might not have considered.
17
18[Quick start guide](#quick-start)
19
20### Features
21* mixes plain classes
22* mixes classes that extend other classes
23* mixes classes that were mixed with `ts-mixer`
24* supports static properties
25* supports protected/private properties (the popular function-that-returns-a-class solution does not)
26* mixes abstract classes (requires TypeScript >= 4.2)
27* mixes generic classes (with caveats [[1](#caveats)])
28* supports class, method, and property decorators (with caveats [[2, 5](#caveats)])
29* mostly supports the complexity presented by constructor functions (with caveats [[3](#caveats)])
30* comes with an `instanceof`-like replacement (with caveats [[4, 5](#caveats)])
31* [multiple mixing strategies](#settings) (ES6 proxies vs hard copy)
32
33### Caveats
341. Mixing generic classes requires a more cumbersome notation, but it's still possible. See [mixing generic classes](#mixing-generic-classes) below.
352. Using decorators in mixed classes also requires a more cumbersome notation. See [mixing with decorators](#mixing-with-decorators) below.
363. ES6 made it impossible to use `.apply(...)` on class constructors (or any means of calling them without `new`), which makes it impossible for `ts-mixer` to pass the proper `this` to your constructors. This may or may not be an issue for your code, but there are options to work around it. See [dealing with constructors](#dealing-with-constructors) below.
374. `ts-mixer` does not support `instanceof` for mixins, but it does offer a replacement. See the [hasMixin function](#hasmixin) for more details.
385. Certain features (specifically, `@decorator` and `hasMixin`) make use of ES6 `Map`s, which means you must either use ES6+ or polyfill `Map` to use them. If you don't need these features, you should be fine without.
39
40## Quick Start
41### Installation
42```
43$ npm install ts-mixer
44```
45
46or if you prefer [Yarn](https://yarnpkg.com):
47
48```
49$ yarn add ts-mixer
50```
51
52### Basic Example
53```typescript
54import { Mixin } from 'ts-mixer';
55
56class Foo {
57 protected makeFoo() {
58 return 'foo';
59 }
60}
61
62class Bar {
63 protected makeBar() {
64 return 'bar';
65 }
66}
67
68class FooBar extends Mixin(Foo, Bar) {
69 public makeFooBar() {
70 return this.makeFoo() + this.makeBar();
71 }
72}
73
74const fooBar = new FooBar();
75
76console.log(fooBar.makeFooBar()); // "foobar"
77```
78
79## Special Cases
80### Mixing Generic Classes
81Frustratingly, it is _impossible_ for generic parameters to be referenced in base class expressions. No matter what, you will eventually run into `Base class expressions cannot reference class type parameters.`
82
83The way to get around this is to leverage [declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html), and a slightly different mixing function from ts-mixer: `mix`. It works exactly like `Mixin`, except it's a decorator, which means it doesn't affect the type information of the class being decorated. See it in action below:
84
85```typescript
86import { mix } from 'ts-mixer';
87
88class Foo<T> {
89 public fooMethod(input: T): T {
90 return input;
91 }
92}
93
94class Bar<T> {
95 public barMethod(input: T): T {
96 return input;
97 }
98}
99
100interface FooBar<T1, T2> extends Foo<T1>, Bar<T2> { }
101@mix(Foo, Bar)
102class FooBar<T1, T2> {
103 public fooBarMethod(input1: T1, input2: T2) {
104 return [this.fooMethod(input1), this.barMethod(input2)];
105 }
106}
107```
108
109Key takeaways from this example:
110* `interface FooBar<T1, T2> extends Foo<T1>, Bar<T2> { }` makes sure `FooBar` has the typing we want, thanks to declaration merging
111* `@mix(Foo, Bar)` wires things up "on the JavaScript side", since the interface declaration has nothing to do with runtime behavior.
112* The reason we have to use the `mix` decorator is that the typing produced by `Mixin(Foo, Bar)` would conflict with the typing of the interface. `mix` has no effect "on the TypeScript side," thus avoiding type conflicts.
113
114### Mixing with Decorators
115Popular libraries such as [class-validator](https://github.com/typestack/class-validator) and [TypeORM](https://github.com/typeorm/typeorm) use decorators to add functionality. Unfortunately, `ts-mixer` has no way of knowing what these libraries do with the decorators behind the scenes. So if you want these decorators to be "inherited" with classes you plan to mix, you first have to wrap them with a special `decorate` function exported by `ts-mixer`. Here's an example using `class-validator`:
116
117```typescript
118import { IsBoolean, IsIn, validate } from 'class-validator';
119import { Mixin, decorate } from 'ts-mixer';
120
121class Disposable {
122 @decorate(IsBoolean()) // instead of @IsBoolean()
123 isDisposed: boolean = false;
124}
125
126class Statusable {
127 @decorate(IsIn(['red', 'green'])) // instead of @IsIn(['red', 'green'])
128 status: string = 'green';
129}
130
131class ExtendedObject extends Mixin(Disposable, Statusable) {}
132
133const extendedObject = new ExtendedObject();
134extendedObject.status = 'blue';
135
136validate(extendedObject).then(errors => {
137 console.log(errors);
138});
139```
140
141### Dealing with Constructors
142As mentioned in the [caveats section](#caveats), ES6 disallowed calling constructor functions without `new`. This means that the only way for `ts-mixer` to mix instance properties is to instantiate each base class separately, then copy the instance properties into a common object. The consequence of this is that constructors mixed by `ts-mixer` will _not_ receive the proper `this`.
143
144**This very well may not be an issue for you!** It only means that your constructors need to be "mostly pure" in terms of how they handle `this`. Specifically, your constructors cannot produce [side effects](https://en.wikipedia.org/wiki/Side_effect_%28computer_science%29) involving `this`, _other than adding properties to `this`_ (the most common side effect in JavaScript constructors).
145
146If you simply cannot eliminate `this` side effects from your constructor, there is a workaround available: `ts-mixer` will automatically forward constructor parameters to a predesignated init function (`settings.initFunction`) if it's present on the class. Unlike constructors, functions can be called with an arbitrary `this`, so this predesignated init function _will_ have the proper `this`. Here's a basic example:
147
148```typescript
149import { Mixin, settings } from 'ts-mixer';
150
151settings.initFunction = 'init';
152
153class Person {
154 public static allPeople: Set<Person> = new Set();
155
156 protected init() {
157 Person.allPeople.add(this);
158 }
159}
160
161type PartyAffiliation = 'democrat' | 'republican';
162
163class PoliticalParticipant {
164 public static democrats: Set<PoliticalParticipant> = new Set();
165 public static republicans: Set<PoliticalParticipant> = new Set();
166
167 public party: PartyAffiliation;
168
169 // note that these same args will also be passed to init function
170 public constructor(party: PartyAffiliation) {
171 this.party = party;
172 }
173
174 protected init(party: PartyAffiliation) {
175 if (party === 'democrat')
176 PoliticalParticipant.democrats.add(this);
177 else
178 PoliticalParticipant.republicans.add(this);
179 }
180}
181
182class Voter extends Mixin(Person, PoliticalParticipant) {}
183
184const v1 = new Voter('democrat');
185const v2 = new Voter('democrat');
186const v3 = new Voter('republican');
187const v4 = new Voter('republican');
188```
189
190Note the above `.add(this)` statements. These would not work as expected if they were placed in the constructor instead, since `this` is not the same between the constructor and `init`, as explained above.
191
192## Other Features
193### hasMixin
194As mentioned above, `ts-mixer` does not support `instanceof` for mixins. While it is possible to implement [custom `instanceof` behavior](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance), this library does not do so because it would require modifying the source classes, which is deliberately avoided.
195
196You can fill this missing functionality with `hasMixin(instance, mixinClass)` instead. See the below example:
197
198```typescript
199import { Mixin, hasMixin } from 'ts-mixer';
200
201class Foo {}
202class Bar {}
203class FooBar extends Mixin(Foo, Bar) {}
204
205const instance = new FooBar();
206
207// doesn't work with instanceof...
208console.log(instance instanceof FooBar) // true
209console.log(instance instanceof Foo) // false
210console.log(instance instanceof Bar) // false
211
212// but everything works nicely with hasMixin!
213console.log(hasMixin(instance, FooBar)) // true
214console.log(hasMixin(instance, Foo)) // true
215console.log(hasMixin(instance, Bar)) // true
216```
217
218`hasMixin(instance, mixinClass)` will work anywhere that `instance instanceof mixinClass` works. Additionally, like `instanceof`, you get the same [type narrowing benefits](https://www.typescriptlang.org/docs/handbook/advanced-types.html#instanceof-type-guards):
219
220```typescript
221if (hasMixin(instance, Foo)) {
222 // inferred type of instance is "Foo"
223}
224
225if (hasMixin(instance, Bar)) {
226 // inferred type of instance of "Bar"
227}
228```
229
230## Settings
231ts-mixer has multiple strategies for mixing classes which can be configured by modifying `settings` from ts-mixer. For example:
232
233```typescript
234import { settings, Mixin } from 'ts-mixer';
235
236settings.prototypeStrategy = 'proxy';
237
238// then use `Mixin` as normal...
239```
240
241### `settings.prototypeStrategy`
242* Determines how ts-mixer will mix class prototypes together
243* Possible values:
244 - `'copy'` (default) - Copies all methods from the classes being mixed into a new prototype object. (This will include all methods up the prototype chains as well.) This is the default for ES5 compatibility, but it has the downside of stale references. For example, if you mix `Foo` and `Bar` to make `FooBar`, then redefine a method on `Foo`, `FooBar` will not have the latest methods from `Foo`. If this is not a concern for you, `'copy'` is the best value for this setting.
245 - `'proxy'` - Uses an ES6 Proxy to "soft mix" prototypes. Unlike `'copy'`, updates to the base classes _will_ be reflected in the mixed class, which may be desirable. The downside is that method access is not as performant, nor is it ES5 compatible.
246
247### `settings.staticsStrategy`
248* Determines how static properties are inherited
249* Possible values:
250 - `'copy'` (default) - Simply copies all properties (minus `prototype`) from the base classes/constructor functions onto the mixed class. Like `settings.prototypeStrategy = 'copy'`, this strategy also suffers from stale references, but shouldn't be a concern if you don't redefine static methods after mixing.
251 - `'proxy'` - Similar to `settings.prototypeStrategy`, proxy's static method access to base classes. Has the same benefits/downsides.
252
253### `settings.initFunction`
254* If set, `ts-mixer` will automatically call the function with this name upon construction
255* Possible values:
256 - `null` (default) - disables the behavior
257 - a string - function name to call upon construction
258* Read more about why you would want this in [dealing with constructors](#dealing-with-constructors)
259
260### `settings.decoratorInheritance`
261* Determines how decorators are inherited from classes passed to `Mixin(...)`
262* Possible values:
263 - `'deep'` (default) - Deeply inherits decorators from all given classes and their ancestors
264 - `'direct'` - Only inherits decorators defined directly on the given classes
265 - `'none'` - Skips decorator inheritance
266
267# Author
268Tanner Nielsen <tannerntannern@gmail.com>
269* Website - [tannernielsen.com](http://tannernielsen.com)
270* Github - [tannerntannern](https://github.com/tannerntannern)
Note: See TracBrowser for help on using the repository browser.