0

質問は基本的には、higher-order componentsの型チェックを一般的なJavaScriptの方法で実装する方法です。型チェックすることで上位コンポーネントの型検証

Hoc1 = (superclass) => class extends superclass { ... } 
class A { ... } 
class B extends Hoc1(A) { ... } 

私は2つの最も顕著なのユーティリティのいずれかの使用を意味:TypeScriptまたはflow

これまでのところ、私は活字体で次のコードが出ている、

interface IAMixin { 
    aMixedMethod(): void 
} 
interface IAMixinConstructor { 
    new(): IAMixin 
} 

const AHoc: <T>(superclass: T) => T & IAMixinConstructor = (superclass) => 
    class extends superclass implements IAMixin { 
    aMixedMethod() {} 
} 

class A { 
    aMethod() {} 
} 
class B extends AHoc(A) { 
    bMethod() {} 
} 

const b = new B(); 

b.aMixedMethod(); // false-positive: incrorrectly reports as missing method 
b.aMethod(); 
b.bMethod(); 
b.cMethod(); // this is correctly caught, though 

私はこのよう

const AMixin: (superclass) => typeof superclass & IAMixinConstructor = 
    (superclass) => class extends superclass implements IAMixin { 
    aMixedMethod() {} 
    } 

ミックスインを書いた場合、それはanyと偽負ミスとしてsuperclassについて考えますcMethodの呼び出しでエラーが発生しました。

これは、少なくともTypeScriptでは可能であるようです。 Object.assignのインスタンスで正しく動作します。しかし、同じ種類の工事が必要ですが、クラスの場合はです。

またはRuby classesのようなクラスタイプが必要ですか?代わりに、戻り値のための実際のインスタンス及びそのクラスのコンストラクタ関数型としてAHocパラメータを定義したもの欠落し

+0

[活字体ハンドブック(HTTPS参照://をwww.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html)を参照してください。 –

+0

新しいTS機能については、https://blog.mariusschulz.com/2017/05/26/typescript-2-2-mixin-classesで読みやすくなっています。 – kirilloid

答えて

1

interface IAMixin { 
    aMixedMethod(): void 
} 

const AHoc: <T>(superclass: new() => T) => new() => (T & IAMixin) = 
    (superclass) => class extends superclass implements IAMixin { 
     aMixedMethod() { } 
    } 

class A { 
    aMethod() {} 
} 
class B extends AHoc(A) { 
    bMethod() {} 
} 

const b = new B(); 

b.aMixedMethod(); // now good 
b.aMethod(); 
b.bMethod(); 
b.cMethod(); // this is correctly caught 
+0

私はエイリアス 'typeクラス = new()=> T'を導入し、それを使うとコードをもっと読みやすくすることが分かりました。 – kirilloid

関連する問題