2016-09-27 10 views
1

常に呼び出された型を返すメソッドを作成しようとしています。同様のことを可能にする "this"型が見つかりましたが、同じクラスの他のインスタンスではなく、リテラル "this"としか互換性がないようです。常に型を返すTypescriptメソッド/「型Xはこの型に割り当てることができません」

abstract class A { 
    // I need a method which always returns the same type for a transformation method, 
    // a clone function would need the same interface 
    abstract alwaysReturnSameType(): this 
} 
class B extends A { 
    x:number 
    constructor(x:number) { 
     this.x = x 
    } 
    alwaysReturnSameType():this { 
     return new B(this.x + 1) // ERROR: Type 'B' is not assignable to type 'this'. 
     // this works, but isn't what I need: return this 
    } 
} 

私はgithubの上のいくつかの非常に長いの問題(例えばhttps://github.com/Microsoft/TypeScript/issues/5863)見てきたが、私はそこに発見される解決策があるかどうかわかりません。あなたがthisにキャストすることができます

はこれを解決する方法はありますか私は、エラーをSUPRESSにキャストする必要があり、すなわちreturn <this> new B()

+0

キーワード** this **をタイプとして使用することはできません。 – toskv

+3

@toskv https://www.typescriptlang.org/docs/handbook/advanced-types.htmlを参照してください。 "多型このタイプ" –

答えて

1

class B extends A { 
    x: number; 

    constructor(x: number) { 
     super(); 
     this.x = x 
    } 

    alwaysReturnSameType(): this { 
     return new B(this.x + 1) as this; 
    } 
} 

code in playground

私は」それがなければなぜうまくいかないのか分からない。


それは実際にそれがnew Bを返す文句という意味があります。
thisを返すと宣言すると、「現在のインスタンス」を意味しますが、新しいインスタンスが異なります。

1

他のクラス(存在しないことは証明できません)の存在下で動作しないため、コードがコンパイルされません。

class B extends A { 
    x:number 
    constructor(x:number) { 
     this.x = x 
    } 
    alwaysReturnSameType():this { 
     return new B(this.x + 1) // ERROR: Type 'B' is not assignable to type 'this'. 
     // this works, but isn't what I need: return this 
    } 
} 

class C extends B { 
    constructor() { super(3); } 
    foo() { } 
} 

let x = new C(); 
let y = x.alwaysReturnSameType(); // y: C, but it's a B 
y.foo(); // fails 

はあなたがreturn this;に必要な、または動的にクラスのインスタンスから独自のコンストラクタ関数を決定し、それを正しく起動する方法を見つけ出すために、より複雑なものをやるthisを返すようにしたい場合。

+0

コンパイラは、拡張クラスを検出すると常にエラーを出力できますが、メソッドを正しくオーバーライドしません。私はこのクラスにキャストしようとしています。クラスの1回の使用ごとに型パラメータをドラッグするよりもずっと面倒です。 –

関連する問題