考虑这种情况(虚拟示例):
class Farmer<A extends Animal<Farmer<A>>>
{
public animal: A;
constructor() {
let a = new Animal(this);
// ...
}
}
class Animal<F extends Farmer<Animal<F>>>
{
public farmer: F;
constructor(f: F) {
this.farmer = f;
}
}
任何人都可以解释为什么在Farmer
构造函数中(我将this
参数传递给new Animal
的原因),上面的代码会引发此错误?
TS2345: Argument of type 'this' is not assignable to parameter of type 'Farmer<Animal<this>>'.
Type 'Farmer<A>' is not assignable to type 'Farmer<Animal<this>>'.
Type 'A' is not assignable to type 'Animal<this>'.
Type 'Animal<Farmer<A>>' is not assignable to type 'Animal<this>'.
Type 'Farmer<A>' is not assignable to type 'this'.
以下解决了这个问题:
class Farmer<A extends Animal<Farmer<A>>>
{
public animal: A;
constructor() {
let a = new Animal(this as Farmer<A>); // works fine
}
}
或者作为替代:
class Farmer<A extends Animal<Farmer<A>>>
{
public animal: A;
constructor() {
let a = new Animal<Farmer<A>>(this); // works fine
}
}
对我来说更奇怪的是:
class Farmer<A extends Animal<Farmer<A>>>
{
// public animal: A; // removed this line
constructor() {
let a = new Animal(this); // now this one works fine too
}
}
虽然前两个解决方案很明确,但是后一个解决方案使我更加怀疑。 谁能解释发生了什么事?
修改
以下方法很好(考虑Animal
构造函数中的可选参数):
class Farmer<A extends Animal<Farmer<A>>>
{
public animal: A;
constructor() {
let a = new Animal();
a.farmer = this; // works fine
}
}
与第一种情况相比,在这里我看不到类型上的任何差异。