0

I have a generic class of typescript with 2 properties as -

export class WrapperModel<T>{
    constructor(private testType: new () => T) {
        this.getNew();
    }

    getNew(): T {
        return new this.testType();
    }
    public Entity: T;
    public ShowLoading: boolean;
}

Then using it as follows -

this.userModel = new WrapperModel<UserProfileModel>(UserProfileModel);

I am assuming it is creating an instance of type UserProfileModel in its constructor.

But when I try with Array type property then it fails. Like when I do -

this.userModel = new WrapperModel<Array<UserProfileModel>>(Array<UserProfileModel>);

The error which I get in above case -

enter image description here

Is it I cannot create an instance of Array property in generics or something else. My need is simple; I want to create instance of Array properties in Generic class.

1 Answer 1

1

The problem is that that at runtime generics are erased, so Array<UserProfileModel> is not really a constructor function, Array is the constructor function so you can write:

var userModel = new WrapperModel<Array<UserProfileModel>>(Array);

This applies for any generic type, not just array:

class Generic<T> {  }
var other = new WrapperModel<Generic<UserProfileModel>>(Generic);

Generally for a generic class there does not appear to be a way to get a constructor for specific type instantiation, only the generic constructor:

// Valid, new get a generic constrcutor
var genericCtor: new <T>() => Generic<T> = Generic;

// Not valid,  Generic<UserProfileModel> is not callable
var genericCtor: new () => Generic<UserProfileModel> = Generic<UserProfileModel>;
Sign up to request clarification or add additional context in comments.

4 Comments

It worked thanks. Is it only pass typeof argument for all generic types?
Sorry not sure I understand the question
I meant to say what if I pass only type of argument as - this.userModel = new WrapperModel<UserProfileModel>(object) <-- object is passed since the type argument is removed right?
You have to pass the class without generic arguments, that does not mean any generic class would too, typescript still checks compatibility, so this will give an error: class Generic<T> { public foo: number } class Generic2<T> { public foo2: number } var other = new WrapperModel<Generic<UserProfileModel>>(Generic2);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.