Typescript 类型脚本3.1.3+;泛型,类型赋值错误
考虑这种情况(虚拟示例): 以下是解决问题的方法:Typescript 类型脚本3.1.3+;泛型,类型赋值错误,typescript,generics,typescript3.0,Typescript,Generics,Typescript3.0,考虑这种情况(虚拟示例): 以下是解决问题的方法: class Farmer<A extends Animal<Farmer<A>>> { public animal: A; constructor() { let a = new Animal(this as Farmer<A>); // works fine } } 与第一种情况相比,这里我看不到任何类型上的差异。哇,通常在TypeScript中,您可以
class Farmer<A extends Animal<Farmer<A>>>
{
public animal: A;
constructor() {
let a = new Animal(this as Farmer<A>); // works fine
}
}
与第一种情况相比,这里我看不到任何类型上的差异。哇,通常在TypeScript中,您可以回避,但这里有相互递归的类型参数,所以您不能。编译器无法验证
A
是否等同于animal最后一个解决方案“有效”的原因是因为Farmer,这正是TypeScript真正关心的。也就是说,Farmer
和Farmer
是等价的类型,没有更多的相互递归需要关注。我不确定是否有人有一个更干净的解决方案不涉及类型断言。。如果不是,我会在某个时候把这些评论变成一个答案。Cheers@jcalz,有用的观点。谢谢我编辑了问题,添加了另一个案例。
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
}
}
class Farmer<A extends Animal<Farmer<A>>>
{
public animal: A;
constructor() {
let a = new Animal();
a.farmer = this; // works fine
}
}