【问题标题】:Generic method in Typescript打字稿中的通用方法
【发布时间】:2017-12-24 21:29:42
【问题描述】:

我有一个抽象类,它有一个抽象的泛型方法,看起来像这样

protected abstract getData<T>(): T[];

然后我有一个扩展这个抽象类的类。由于getData 是抽象的,我必须在子类中实现它。

它看起来像这样

protected getDataList<T>(): T[] {
    return this.databaseService().getSomethingList();
}

getSomethingList()returns Something[]

我收到以下错误

类型“Something[]”不可分配给类型“T[]”。

我尝试了一些方法来解决此错误,但似乎必须使子实现也通用化才能让 Typescript 满意。在我将 Typescript 从 2.2.1 升级到 2.4.1 之前,上述实现一直很好。

所以我想知道如何使我的代码再次与 Typescript 2.4.1 兼容?

【问题讨论】:

  • 泛型方法不能返回非泛型字段。您要么必须使 Something 扩展通用对象,要么将返回类型更改为对象。
  • 你有 getData 和 getDataList。那是错字吗?你可以这样做吗?受保护的抽象 getData(): T[]; protected getData(): Something[] { return this.databaseService().getSomethingList(); }
  • @JGFMK sry,我做例子的时候没想到。

标签: typescript generics


【解决方案1】:

你的实现:

protected getDataList<T>(): T[] {
    return this.databaseService().getSomethingList();
}

T 没有以任何方式被替换是错误的。这被称为无用的泛型 https://basarat.gitbooks.io/typescript/docs/types/generics.html

修复

protected getDataList(): Something[] {
    return this.databaseService().getSomethingList();
}

【讨论】:

    【解决方案2】:

    我相信您正在尝试设置它,以便整个抽象基础由派生实例必须具体化的特定类型参数化。以下是你的做法:

    abstract class Foo<T> {
        protected abstract getData(): T[];
    }
    
    class Something { }
    class SomethingFoo extends Foo<Something> {
        protected getData(): Something[] {
            // implement here
        }
    }
    

    请注意,函数本身没有参数化,因为函数的调用者不是决定这个函数将返回什么类型的人。相反,包含类型是参数化的,它的任何派生都指定了相应的类型参数。

    【讨论】:

      【解决方案3】:

      你也可以在你的类中使用类似这样的东西来定义Something[]:

      interface Something{
          foo: foo,
          var: var
      }
      

      【讨论】:

        猜你喜欢
        • 2019-06-20
        • 2020-06-20
        • 2016-02-18
        • 2020-12-22
        • 2013-04-15
        • 1970-01-01
        • 2020-01-10
        • 2016-10-26
        相关资源
        最近更新 更多