File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed
Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change 1+
2+ // Each mixin is a traditional ES class
3+ class Jumpable {
4+ jump() {}
5+ }
6+
7+ class Duckable {
8+ duck() {}
9+ }
10+
11+ // Including the base
12+ class Sprite {
13+ x = 0;
14+ y = 0;
15+ }
16+
17+ // Then you create an interface which merges
18+ // the expected mixins with the same name as your base
19+ interface Sprite extends Jumpable, Duckable {}
20+ // Apply the mixins into the base class via
21+ // the JS at runtime
22+ applyMixins(Sprite, [Jumpable, Duckable]);
23+
24+ let player = new Sprite();
25+ player.jump();
26+ console.log(player.x, player.y);
27+
28+ // This can live anywhere in your codebase:
29+ function applyMixins(derivedCtor: any, constructors: any[]) {
30+ constructors.forEach((baseCtor) => {
31+ Object.getOwnPropertyNames(baseCtor.prototype).forEach((name) => {
32+ Object.defineProperty(
33+ derivedCtor.prototype,
34+ name,
35+ Object.getOwnPropertyDescriptor(baseCtor.prototype, name)
36+ );
37+ });
38+ });
39+ }
40+
41+ This pattern relies less on the compiler, and more on your codebase to ensure both runtime and type-system are correctly kept in sync.
You can’t perform that action at this time.
0 commit comments