【问题标题】:Unresolved type T when creating an Array<T> with generic in Typescript在 Typescript 中使用泛型创建 Array<T> 时未解析的类型 T
【发布时间】:2016-09-10 03:21:27
【问题描述】:

所以我正在尝试创建一个对象,该对象具有一系列我希望项目成为通用的项目,但我收到错误 unresolved type T

export class AllocationInvestorVO {
    public name: string;
    public id: string;
    public projects: Array<T>; //ERROR: unresolved type T
}

我的目标是我们在 Java 中看到的多态行为,我们可以创建一个可以扩展为 ArrayList 的 List 对象,例如:

如何创建一个基本类型为 ProjectArray,它可以多态化为 ProjectXProjectY 类型的数组。

【问题讨论】:

    标签: typescript typescript1.8 typescript1.4


    【解决方案1】:

    如果您希望projects 是通用的,那么您需要首先将AllocationInvestorVO 类声明为通用:

    export class AllocationInvestorVO<T> {
        public name: string;
        public id: string;
        public projects: Array<T>; // ok
    }
    

    否则T无法解析。
    如果你想为这个T 打下基础,那么:

    export class AllocationInvestorVO<T extends Project> {
        public name: string;
        public id: string;
        public projects: Array<T>;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-22
      • 1970-01-01
      • 2020-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-22
      • 1970-01-01
      相关资源
      最近更新 更多