Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm trying to create a new object of a type parameter in my generic class. In my class "View" I have 2 list of objects of generic type passed as type parameters, but when I try to make "new T()" typescript says "Could not find symbol 'T'" ...

This is the code:

Can I create objects from a generic type?

Thanks ;)

share|improve this question

1 Answer 1

up vote 9 down vote accepted

Because the compiled JavaScript has all the type information erased, you can't use T to new up an object.

You can do this in a non-generic way by passing the type into the constructor.

class TestOne {
    hi() {
        alert('Hi');
    }
}

class TestTwo {
    constructor(private testType) {

    }
    getNew() {
        return new this.testType();
    }
}

var test = new TestTwo(TestOne);

var example = test.getNew();
example.hi();

You could extend this example using generics to tighten up the types:

class TestBase {
    hi() {
        alert('Hi from base');
    }
}

class TestSub extends TestBase {
    hi() {
        alert('Hi from sub');
    }
}

class TestTwo<T extends TestBase> {
    constructor(private testType) {
    }

    getNew() : T {
        return new this.testType();
    }
}

//var test = new TestTwo<TestBase>(TestBase);
var test = new TestTwo<TestSub>(TestSub);

var example = test.getNew();
example.hi();
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.