
1. 믹스인
타입스크립트에서 믹스인은 여러 클래스의 기능을 조합해 새로운 클래스를 만드는 패턴으로, 이를 통해 코드의 재사용성을 높여줍니다. 타입스크립트에서 믹스인을 구현하기 위해 먼저 함수를 정의합니다.
function Mixin<T extends new (...args: any[]) => {}>(Base: T) {
return class extends Base {
mixinMethod() {
console.log('Mixin method called');
}
};
}
2. 믹스인 기본 클래스 정의
먼저 믹스인이 결합될 기본 클래스를 정의해줍니다.
class Robot {
move() {
console.log('Robot is moving!');
}
}
다음은 믹스인을 적용해 새로운 클래스를 만들어줍니다. 믹스인은 보통 함수로 정의됩니다.
function Mixin<T extends new (...args: any[]) => {}>(Base: T) {
return class extends Base {
mixinMethod() {
console.log('Mixin method called');
}
};
}
class Robot {
move() {
console.log('Robot is moving!');
}
}
const MixinRobot = Mixin(Robot);
const instance = new MixinRobot();
instance.mixinMethod(); // "Base method called"
instance.move(); // "Mixin method called"
GitHub - Koras02/typescript-bloging
Contribute to Koras02/typescript-bloging development by creating an account on GitHub.
github.com
LIST
'Front-End > TypeScript' 카테고리의 다른 글
[Typescript] 19장 네임스페이스 (0) | 2025.04.07 |
---|---|
[TypeScript] 18장 모듈 (0) | 2025.04.01 |
[Typescript] 16장 JSX (0) | 2025.03.24 |
[Typescript] 15장 이터러블 타입 (0) | 2025.03.22 |
[TypeScript] 14장 유티릴티 타입 (1) | 2025.03.20 |