2017-06-14 1 views
2

ミックスインクラスで実装されている抽象メソッドをTypescript Mixinに追加します。このようなもの。typescriptミックスインの抽象メソッド

class MyBase { 
} 

type Constructor<T = {}> = new (...args: any[]) => T; 

function Mixin<TBase extends Constructor<MyBase>>(Base: TBase) { 
    return class extends Base { 

    baseFunc(s: string) {}; 

    doA() 
    { 
     this.baseFunc("A"); 
    } 
    } 
}; 

class Foo extends Mixin(MyBase) { 
    constructor() 
    { 
     super(); 
    } 

    baseFunc(s: string) 
    { 
     document.write("Foo "+ s +"... ")    
    } 
}; 

さて、これは動作しますが、私は実際にそれがfooで実装されますことを確認するために、抽象的でミックスインでbaseFuncをしたいのですが。 abstract baseFunc(s:string);は、抽象クラスを持っていなければならないと言っています。

答えて

2

匿名クラスは抽象クラスではありませんが、依然として抽象クラスであることを宣言できますこのように:

class MyBase { 
} 

type Constructor<T = {}> = new (...args: any[]) => T; 

function Mixin(Base: Constructor<MyBase>) { 
    abstract class AbstractBase extends Base { 
    abstract baseFunc(s: string);  
    doA() 
    { 
     this.baseFunc("A"); 
    } 
    } 
    return AbstractBase; 
}; 


class Foo extends Mixin(MyBase) { 
    constructor() 
    { 
     super(); 
    } 

    baseFunc(s: string) 
    { 
     document.write("Foo "+ s +"... ")    
    } 
}; 
+0

私はそれを試みたと思った!なぜ抽象クラスを返さないのですか? – Roddy

+0

この例では、MyBaseのメソッドとプロパティが失われています。 'Mixin >(Base:B)'で修正できます。 –

関連する問題