Last active
June 22, 2022 06:38
-
-
Save maple5233/5f34cc1dc068342eb79210a5126b635d to your computer and use it in GitHub Desktop.
Multiple inheritance in typescript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// uses annotations in ts to achieve effects similar to the default interface implementation | |
// thereby achieving multiple inheritance | |
// TS使用注解实现类似默认接口实现的效果,从而实现多继承 | |
type Logger = (log: string) => void; | |
function setLoggerCategory(logCategory: string) { | |
return function _DecoratorName<T extends { new (...args: any[]): {} }>(constructor: T) { | |
return class extends constructor implements hasLogger { | |
// @ts-expect-error | |
logger: Logger; | |
constructor(...args: any[]) { | |
super(...args); | |
if (!('logger' in this)) { | |
// @ts-ignore | |
this.logger = (log: string) => { console.log(`[${logCategory}]`, log) }; | |
} | |
} | |
}; | |
}; | |
} | |
/** | |
* 因为装饰器是运行时,所以无法自动修正TS类型,只能export一个interface出去 方便业务extends | |
*/ | |
interface hasLogger { | |
logger: Logger; | |
} | |
interface A extends hasLogger {} | |
@setLoggerCategory('23333') | |
class A { | |
bbb() { | |
return '1'; | |
} | |
} | |
interface B extends hasLogger {} | |
@setLoggerCategory('114514') | |
class B { | |
constructor() { | |
this.logger = (log: string) => { console.error(`[what!!!]`, log) }; | |
} | |
} | |
const a = new A(); | |
a.logger('666'); | |
const b = new B(); | |
b.logger('888') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment