【发布时间】:2017-05-23 03:35:59
【问题描述】:
我试图用两个泛型调用一个函数,但收到一个类型不可赋值的错误。
abstract class foo<T1, T2> {
protected readonly generic1 : T1;
protected readonly generic2 : T2
constructor(t1: T1, t2: T2) {
this.generic1 = t1;
this.generic2 = t2;
}
}
class bar<T1, T2> extends foo<T1, T2>
{
constructor()
{
super(new someObject(), new otherObject());
}
public myFunction()
{
// I want to retain type information
this.generic1.someMethod();
this.generic2.otherMethod();
}
}
// Objects that have nothing in common, so can't interface them
class someObject {
public someMethod() { };
}
class otherObject {
public otherMethod() { };
}
【问题讨论】:
-
那是因为 "" 是 'string' 类型,而 T1 和 T2 不一定。 bar 是否实现了 foo 的字符串版本?
-
您在编辑中修改了代码,但问题未解决。
T1可以是任何东西,所以someObject不能总是T1。 -
为什么
bar是通用的?为什么不直接写class bar extends foo<someObject, otherObject>?
标签: javascript generics typescript