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
}
}