0

Having a problem with Typescript's Generics where the type is undefined in the scope of the generic function or class. I can't find any documentation on this though I would assume it is by design. Is there a way to achieve what I am trying to, type-safely?

function test<T>() {
    return new T();
}

class TestClass<T> {
    public build(): T {
        return new T();
    }
}

Link to Play:

http://www.typescriptlang.org/Playground/#src=function%20test%3CT%3E()%20%7B%0A%09return%20new%20T()%3B%0A%7D%0A%0Aclass%20TestClass%3CT%3E%20%7B%0A%09public%20build()%3A%20T%20%7B%0A%09%09return%20new%20T()%3B%0A%09%7D%0A%7D%0A

dave
  • 1,127
  • 2
  • 10
  • 26
  • 1
    For explanation of non-generic version, see http://stackoverflow.com/questions/13407036/how-does-typescript-interfaces-with-construct-signatures-work – Ryan Cavanaugh Nov 13 '15 at 04:36

1 Answers1

3

TypeScript generics (unlike other languages like C#) are compile time only. So you cannot use them in runtime positions e.g. new T.

Is there a way to achieve what I am trying to, type-safely

Pass the constructor explicitly. e.g.

class TestClass<T> {
    public build(x:{new ():T}): T {
        return new x();
    }
}

Here x:{new ():T} I am saying that x is something that when called with new gives an instance of T.

basarat
  • 261,912
  • 58
  • 460
  • 511