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

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

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.