Open kennyd98 opened 7 years ago
ORIGINAL - typescript document 번역
var calculatorMixin = Base => class extends Base {
calc() { }
};
var randomizerMixin = Base => class extends Base { randomize() { } };
class Foo { } class Bar extends calculatorMixin(randomizerMixin(Foo)) { }
* 참고
- [MDN Mixin description](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Mix-ins)
- [Real Mixins with JavaScript Classes](http://justinfagnani.com/2015/12/21/real-mixins-with-javascript-classes/)
### Mix-in 생성자 타입
* `any[]` 타입의 single rest argument
* object-like 타입의 반환
* 예시, `X` 가 특정 object-like 타입인 경우 아래와 같은 게 Mix-in 생성자 타입
```javascript
constructor (...args: any[]) {
return X;
}
extend
하는 클래스any[]
타입의 single rest argument를 가져야 하고, 이는 super(...args)
와 같이 부모생성자를 호출할 때 쓰임{ new(...args: any[]) => A } & { new(s: string) => B }
가 섞인 경우, new(s: string) => A & B
와 같은 생성자 시그니쳐가 됨.class Point {
constructor(public x: number, public y: number) {}
}
class Person {
constructor(public name: string) {}
}
type Constructor<T> = new(...args: any[]) => T;
function Tagged<T extends Constructor<{}>>(Base: T) {
return class extends Base {
_tag: string;
constructor(...args: any[]) {
super(...args);
this._tag = "";
}
}
}
const TaggedPoint = Tagged(Point);
let point = new TaggedPoint(10, 20);
point._tag = "hello";
class Customer extends Tagged(Person) {
accountBalance: number;
}
let customer = new Customer("Joe");
customer._tag = "test";
customer.accountBalance = 0;
WithLocation
함수는 getLocation
메소드가 추가되고 'Point' 인터페이스를 만족하여 'x', 'y' 프로퍼티가 있는 subclass 팩토리를 구현함.interface Point {
x: number;
y: number;
}
const WithLocation = <T extends Constructor<Point>>(Base: T) =>
class extends Base {
getLocation(): [number, number] {
return [this.x, this.y];
}
}
Mix-in 이란?
예시 1
function Timestamped(Base: TBase) {
return class extends Base {
timestamp = Date.now();
};
}
class User { name: string;
}
// Create a new class by mixing "Timestamped" into "User" const TimestampedUser = Timestamped(User);
// Instantiate the new "TimestampedUser" class const user = new TimestampedUser("John Doe");
// We can now access properties from both the "User" class // and our "Timestamped" mixin in a type-safe manner console.log(user.name); console.log(user.timestamp);
User
클래스에tag
프로퍼티를 추가하려면?// Instantiate the new "TaggedUser" class const user = new TaggedUser("John Doe");
// We can now access properties from both the "User" class // and our "Tagged" mixin in a type-safe manner user.name = "Jane Doe"; user.tag = "janedoe";
예시 4 - 여러 Mix-in 동시에 사용하기