2016-09-25 77 views
3

我试图找出如何得到这个正常工作:打字稿:如何得到一个子类的方法返回父这个

class A { 
    john(): B { 
     return this; // <-- ERROR HERE 
    } 
} 

class B extends A { 
    joe(): B { 
     return this; 
    } 
} 

所以我可以做方法链接:

let instance = new B(); 
instance.john().joe(); 

当然,TypeScript抱怨this不符合B的类型。

+0

因为B也是A,所以你不需要“parent this”。 – AlexG

回答

7

只需使用this关键字作为方法的返回类型返回this

class A { 
    john(): this { 
     return this; 
    } 
} 

class B extends A { 
    joe(): this { 
     return this; 
    } 
} 

let instance = new B(); 
instance.john().joe(); 

您也可以省略返回类型。打字稿会推断返回类型为this,因为这些方法返回this

class A { 
    john() { 
     return this; 
    } 
} 

class B extends A { 
    joe() { 
     return this; 
    } 
} 

此功能称为Polymorphic this types和打字稿1.7是introduced。有关详细信息,请参见GitHub PR

相关问题