Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I tell TypeScript that a Generic type has a constructor?

I think I can do something like this to create a new instance of a Generic in TypeScript:

class Tree<T extends SomeInterface> {

    constructor(private elementType: {new(): T}) {
    }

    public Grow() {
        var newElement: T = new this.elementType();
        // ...
    }
}

But is there any way to let TypeScript know that a Generic has a new()? In other words, is there any way to get something like this to work?

class Tree<T extends SomeInterface> { // <-- Modify the constraint?
    public Grow() {
        var newElement: T = new T();
        // ...
    }
}
like image 622
Eric Avatar asked Oct 28 '15 15:10

Eric


1 Answers

But is there any way to let TypeScript know that a Generic has a new()? In other words, is there any way to get something like this to work?

Not Exactly. Reason is that you still need to pass in the entity that will New up the object for you. You can't just use the compile time constraint<T> as a runtime new T.

interface SomeInterface{    
}

interface SomeInterfaceConstructor<T extends SomeInterface>{
    new (): T;
}


class Tree<T extends SomeInterface> {
    constructor(private elementType: SomeInterfaceConstructor<T>) {
    }
    public Grow() {
        var newElement = new this.elementType();
        // ...
    }
}
like image 177
basarat Avatar answered Sep 19 '22 23:09

basarat