-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path04.1.mixing-classes.ts
40 lines (31 loc) · 1002 Bytes
/
04.1.mixing-classes.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#support-for-mix-in-classes
// not very well documented, unfortunately
// it's not a typescript feature, but JS!
// MDN link:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Mix-ins
// this is not (!!!) multiple inheritance
// it's like default implementation in java, traits in php, etc
type ConstructorType<T> = new (...args: any[]) => T;
class Animal {}
class Mammal extends Animal {}
class Mouse extends Mammal {}
// as plain js
function teachToFlyJavascript(classToTeach: any) {
return class extends classToTeach {
public ibelieveICanfly() {
return "fly!";
}
};
}
function teachToFly<TC extends ConstructorType<{}>>(classToTeach: TC) {
return class extends classToTeach {
public ibelieveICanfly() {
return "fly!";
}
};
}
const Bird = teachToFly(Animal);
const Bat = teachToFly(Mouse);
const bat = new Bat();
bat.ibelieveICanfly();
export {};