简体   繁体   English

接口字段应具有实现该接口的类的类型-typescript

[英]Interface field should have type of the class that implements that interface - typescript

I am wondering if this is achievable in Typescript. 我想知道这在Typescript中是否可以实现。

interface Pine {

    child : <The class that implements this interface>
}

class Vine implements Pine {

    child : Vine // this is enforced to be Vine, rather than any object that implements Pine.
}

I know from this question that you cannot do it in Java, but what about TS? 这个问题中我知道您无法用Java做到这一点,但是TS呢? I have looked up tslang doc without fruition. 我查了一下tslang doc却没有结果。

You can use Generics. 您可以使用泛型。 eg : 例如:

interface Base<T> {
    child: T;
}

class Derived implements Base<string> {
    child: string;
} 

class Derived2 implements Base<number> {
    child: number;
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM