[英]Typescript generics : not assignable to type T
Here's my code : 这是我的代码:
interface IDoc {
doSomething(): void
}
class IDocFoo implements IDoc {
doSomething(): void {
console.log('Do doSomething');
}
}
class IDocFactory {
getIDocInstance<T extends IDoc>(): T {
return new IDocFoo();
}
}
This code is reduced version of my code, of course. 当然,此代码是我的代码的简化版本。
Typescript shows me an error : Type 'IDocFoo' is not assignable to type 'T'
and I don't understand why. 打字稿给我显示一个错误:不能将
Type 'IDocFoo' is not assignable to type 'T'
,我不明白为什么。 Is anybody can explain me why ? 有人能解释我为什么吗?
The full error message is: 完整的错误消息是:
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'.
The compiler cannot be sure what type you will pass into getIDocInstance()
, and it is possible that you could pass in an incompatible type, eg: 编译器无法确定将传递给
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>();
To achieve what you want you'd have to pass the specific class into the factory constructor. 为了实现所需的功能,您必须将特定的类传递给工厂构造函数。 See this answer .
看到这个答案 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.