【问题标题】:How to solve `Argument of type _ is not assignable to parameter of type 'T1'.` when using multiple generics使用多个泛型时如何解决“_类型的参数不可分配给“T1”类型的参数。
【发布时间】: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() { };
}

Typescript Playground

【问题讨论】:

  • 那是因为 "" 是 'string' 类型,而 T1 和 T2 不一定。 bar 是否实现了 foo 的字符串版本?
  • 您在编辑中修改了代码,但问题未解决。 T1 可以是任何东西,所以someObject 不能总是T1
  • 为什么bar 是通用的?为什么不直接写class bar extends foo&lt;someObject, otherObject&gt;

标签: javascript generics typescript


【解决方案1】:

问题是您将string 传递给未指定的类型参数T1T2。你怎么能说字符串在这两种类型中都是有效值?

如果你说

class bar extends foo<string, string>

然后它会工作。但这似乎不是你想要完成的。你想做什么?


您的扩展示例:

这里没有任何改变。为什么要使bar 本身具有通用性?看起来bar 将通过具体类来满足foo 的泛型,这意味着bar 根本不需要泛型。

class bar extends foo<someObject, otherObject>

【讨论】:

  • 我扩展了我的例子
  • 哦,太简单了。谢谢!
猜你喜欢
  • 2022-06-24
  • 2020-06-18
  • 2019-06-24
  • 2021-06-14
  • 2021-11-20
  • 2021-10-18
  • 2019-09-23
  • 2021-02-03
相关资源
最近更新 更多