常に呼び出された型を返すメソッドを作成しようとしています。同様のことを可能にする "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()
キーワード** this **をタイプとして使用することはできません。 – toskv
@toskv https://www.typescriptlang.org/docs/handbook/advanced-types.htmlを参照してください。 "多型このタイプ" –