2016-08-16 12 views
0

「メンバ変数」を静的型ではなく(インターフェイスを使用せずに)「拡張オブジェクト」として定義する方法はありますか?メンバ変数をTypeScriptで拡張型として宣言する方法は?

単にこの擬似コードのようなもの:

class Foo { 

    bar -> extends Rectangle; 
    constructor(barInstance:IRectangle){ 
     this.bar = barInstance; 

     this.bar.getArea(); //<-- is code completed because interface IRectangle 

     // no type error 
     this.bar.someCustomFunction = function() { 
     } 
    } 

} 

代わりの

class Foo { 
    bar: IRectangle; 
    //or 
    bar:Rectangle; 
} 

私は型エラーを取得せずに、基本クラスまたはインタフェースで定義されていないプロパティを追加するだけでなく、コード補完を取得することができますこの方法ベースクラスから。 Heh、怠惰な厳密なタイピング?

答えて

0

制限されたジェネリック型のパラメータを考えてみましょう。

interface Base { 
    prop: number; 
} 

interface Child extends Base { 
    thing: string; 
} 

class Foo<T extends Base> { 
    bar: T 
} 

var foo = new Foo<Child>(); 
foo.bar.thing; // now permitted by the type checker 
+0

明示的に '事物'を定義することなくこれを行うが、型エラーを発生させることなく動的に割り当てるだけでなく、getコードヒント... this.bar.thing =()=> {return true;}のようなものです。に入力するか、 FlavorScape

+0

クラスにジェネリック型のインスタンスをコンストラクタ引数として渡すと、例えば、オブジェクトリテラルであり、その型が推論される。私はインスタンス化の後に新しいプロパティを割り当て、それらの型チェックを取得するためのソリューションがあるかどうかはわかりません。このようなパターンは静的解析を混乱させる傾向があります。 –

+0

後で追加のプロパティを実際に引き出す必要がある場合は、それらを名前付きインターフェイスのオプションメンバーにします。 –

0

私はあなたを理解していることを完全にわからないんだけど、もしそうなら、このような何か:私はしたい

interface IRectangle { 
    getArea(): void; 
} 

class Rectangle implements IRectangle { 
    getArea(): void {} 
    someCustomFunction(): void {} 
} 

class Foo<T extends IRectangle> { 
    bar: T; 

    constructor(barInstance: T){ 
     this.bar = barInstance; 
     this.bar.getArea(); 

     // no type error 
     if (this.bar instanceof Rectangle) { 
      (this.bar as any as Rectangle).someCustomFunction = function() {} 
     } 
    } 
} 

code in playground

0

交差点の種類

interface IRectangle { 
    getArea:() => number; 
} 

class Foo { 
    bar: IRectangle & { [key: string]: any; }; 

    constructor(barInstance:IRectangle){ 
     this.bar = barInstance; 

     this.bar.getArea(); //<-- is code completed because interface IRectangle 

     // no type error 
     this.bar.someCustomFunction = function() { 
     } 
    } 
} 
関連する問題