打字稿,自我回归通用

时间:2015-07-17 23:24:02

标签: javascript generics interface typescript

我正在开发一个实现通用接口的类,如:

interface World<T> { get(): T; }
class Hello implements World< Hello > { get(){ return this } }

但后来我在想如果另一个类Hello以外的类会实现World接口,那么使用World< AnotherClass >的内容我会想到像World< World >这样的东西因此,无论我在哪里实现World界面,它都可以是永久性的,但看起来像Typescript不接受这种语法,有没有更好的方法呢?,也许有办法解决它?

1 个答案:

答案 0 :(得分:1)

我很抱歉,但不清楚你的意思是“所以无论我在哪里实现World界面,它都可以永久保存”。也许你只想要一个非通用的界面?

interface World {
  get(): World;
}

class Hello implements World {
  get() {
    return this;
  }
  hello() {
    console.log("hello");
  }
}

class AnotherClass implements World {
  get() {
    return this;
  }
  anotherClass() {
    console.log("another class");
  }
}

var h = new Hello();
var ac = new AnotherClass();

var testH = h.get();  //testH is implicitly typed as Hello
var testAC = ac.get();  //testAC is implicitly typed as AnotherClass

//these all work.
var testWorld : World;
testWorld = h.get();
testWorld = ac.get();
相关问题