简体   繁体   中英

Generics in Typescript - Undefined T

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

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

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

Pass the constructor explicitly . eg

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM