打字稿泛型:不可分配给T型

时间:2019-07-28 10:01:30

标签: typescript typescript-generics

这是我的代码:

interface IDoc {
  doSomething(): void
}

class IDocFoo implements IDoc {
  doSomething(): void {
    console.log('Do doSomething');
  }
}

class IDocFactory {
  getIDocInstance<T extends IDoc>(): T {
    return new IDocFoo();
  }
}

当然,此代码是我的代码的简化版本。

打字稿给我看了一个错误:Type 'IDocFoo' is not assignable to type 'T',我不明白为什么。有人可以解释我为什么吗?

1 个答案:

答案 0 :(得分:1)

完整的错误消息是:

Type 'IDocFoo' is not assignable to type 'T'.
  'IDocFoo' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'IDoc'.

编译器不能确定将传递给getIDocInstance()的哪种类型,并且可能传递不兼容的类型,例如:

interface IDoc {
  doSomething(): void
}

class IDocFoo implements IDoc {
  doSomething(): void {
    console.log('Do doSomething');
  }
}

class IDocBar implements IDoc {
  doSomething(): void {
    console.log('Do doSomething');
  }
  doSomethingElse(): void {
    console.log('Do doSomethingElse');
  }
}

class IDocFactory {
  // This will not compile as before, because as the error says, you may pass a
  // different subtype of 'Idoc' to the method; one that IDocFoo is not
  // assignable to.
  static getIDocInstance<T extends IDoc>(): T {
    return new IDocFoo();
  }
}

// Here is an example of how you might pass a different subtype of IDocFoo to
// the factory method.
IDocFactory.getIDocInstance<IDocBar>();

要实现您想要的目标,您必须将特定的类传递给工厂构造函数。参见this answer