始终 returns 拥有类型的 Typescript 方法 / "type X not assignable to type this"
Typescript method which always returns own type / "type X not assignable to type this"
我正在尝试编写一个始终returns调用它的类型的方法。我发现 "this" 类型允许类似的东西,但它似乎只与文字 "this" 兼容,而不与相同 class.[=15 的其他实例兼容=]
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),但我不确定是否可以找到解决方案。
有没有办法解决这个问题,还是我应该强制转换以抑制错误,即 return <this> new B()
您可以将其转换为 this
:
class B extends A {
x: number;
constructor(x: number) {
super();
this.x = x
}
alwaysReturnSameType(): this {
return new B(this.x + 1) as this;
}
}
我不确定为什么没有它就不能工作。
它抱怨 returning new B
.
实际上是有道理的
当你声明你 return this
时,它意味着 "the current instance",但新实例是不同的。
您的代码无法编译,因为它在存在其他 classes(无法证明不存在)的情况下无法工作。
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
你需要 return this;
,或者做更复杂的事情来弄清楚如何从 class实例并正确调用它。
我正在尝试编写一个始终returns调用它的类型的方法。我发现 "this" 类型允许类似的东西,但它似乎只与文字 "this" 兼容,而不与相同 class.[=15 的其他实例兼容=]
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),但我不确定是否可以找到解决方案。
有没有办法解决这个问题,还是我应该强制转换以抑制错误,即 return <this> new B()
您可以将其转换为 this
:
class B extends A {
x: number;
constructor(x: number) {
super();
this.x = x
}
alwaysReturnSameType(): this {
return new B(this.x + 1) as this;
}
}
我不确定为什么没有它就不能工作。
它抱怨 returning new B
.
实际上是有道理的
当你声明你 return this
时,它意味着 "the current instance",但新实例是不同的。
您的代码无法编译,因为它在存在其他 classes(无法证明不存在)的情况下无法工作。
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
你需要 return this;
,或者做更复杂的事情来弄清楚如何从 class实例并正确调用它。