CommonSenseCode
CommonSenseCode

Reputation: 25409

Unresolved type T when creating an Array<T> with generic in Typescript

So I'm trying to create an object which has an arreay of projects I want projects to be a generic of but I'm getting error unresolved type T:

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

What I am aiming for is the polymorphism behavior we see in Java, that we can create a List object which can be extended to ArrayList for example:

How to Create an Array that Base type is for example Project and it can be polymorphed into Array of type ProjectX or ProjectY.

Upvotes: 0

Views: 2126

Answers (1)

Nitzan Tomer
Nitzan Tomer

Reputation: 164297

If you want the projects to be generic then you need to first declare the AllocationInvestorVO class as generic:

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

Otherwise T can't be resolved.
If you want to have a base for this T then:

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

Upvotes: 1

Related Questions