Skip to content

Commit 9eef5a0

Browse files
committed
fix: support plugins that return an empty object
BREAKING CHANGE: `.plugin([plugin1, plugin2])` is now `.plugin(plugin1, plugin2)`
1 parent 065a6b3 commit 9eef5a0

File tree

1 file changed

+18
-9
lines changed

1 file changed

+18
-9
lines changed

src/index.ts

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,9 @@ type Constructor<T> = new (...args: any[]) => T;
1313
* @author https://stackoverflow.com/users/2887218/jcalz
1414
* @see https://stackoverflow.com/a/50375286/10325032
1515
*/
16-
type UnionToIntersection<Union> = (Union extends any
17-
? (argument: Union) => void
18-
: never) extends (argument: infer Intersection) => void // tslint:disable-line: no-unused
16+
type UnionToIntersection<Union> = (
17+
Union extends any ? (argument: Union) => void : never
18+
) extends (argument: infer Intersection) => void // tslint:disable-line: no-unused
1919
? Intersection
2020
: never;
2121

@@ -31,16 +31,25 @@ export class Base {
3131
static plugins: TestPlugin[] = [];
3232
static plugin<
3333
S extends Constructor<any> & { plugins: any[] },
34-
T extends TestPlugin | TestPlugin[]
35-
>(this: S, plugin: T) {
34+
T1 extends TestPlugin,
35+
T2 extends TestPlugin[]
36+
>(this: S, plugin: T1, ...p2: T2) {
3637
const currentPlugins = this.plugins;
38+
let newPlugins: (TestPlugin | undefined)[] = [
39+
...(plugin instanceof Array
40+
? (plugin as TestPlugin[])
41+
: [plugin as TestPlugin]),
42+
...p2,
43+
];
3744

3845
const BaseWithPlugins = class extends this {
39-
static plugins = currentPlugins.concat(plugin);
46+
static plugins = currentPlugins.concat(
47+
newPlugins.filter((plugin) => !currentPlugins.includes(plugin))
48+
);
4049
};
4150

42-
type Extension = ReturnTypeOf<T>;
43-
return BaseWithPlugins as typeof BaseWithPlugins & Constructor<Extension>;
51+
return BaseWithPlugins as typeof BaseWithPlugins &
52+
Constructor<UnionToIntersection<ReturnTypeOf<T1> & ReturnTypeOf<T2>>>;
4453
}
4554

4655
static defaults<S extends Constructor<any>>(this: S, defaults: Options) {
@@ -59,7 +68,7 @@ export class Base {
5968
// apply plugins
6069
// https://stackoverflow.com/a/16345172
6170
const classConstructor = this.constructor as typeof Base;
62-
classConstructor.plugins.forEach(plugin => {
71+
classConstructor.plugins.forEach((plugin) => {
6372
Object.assign(this, plugin(this, options));
6473
});
6574
}

0 commit comments

Comments
 (0)