Moshe Gottlieb
Moshe Gottlieb

Reputation: 4003

Generic type treated as a value in typescript

While trying out generics in typescript, I failed miserably with a cryptic error message from typescript.
I tried creating a wrapper to create classes with a common base class, but I'm getting this error:
'T' only refers to a type, but is being used as a value here. ts(2693)
Here is the code:


class Test {
    constructor(i: number) {
        
    }
}

class Test1 extends Test {

}
class Test2 extends Test {

}

function f<T extends Test>(n:number): T {
    return new T(n)
}

The following works, but is not generic:

function f1(n: number): Test1 {
    return new Test1(n)
}

Here's the typescript playground.

Can someone explain what's going on here, what should I do to fix this?
Also tried creating an interface that defines a required CTOR, but it doesn't seem to be supported.

Upvotes: 1

Views: 1639

Answers (1)

smnbbrv
smnbbrv

Reputation: 24541

You cannot call it that way - generic types define only types and do not exist in javascript.

What you can do is passing your class as another argument

function f<T extends Test>(clss: new() => T, n:number): T {
    return new T(n)
}

Then the type of the class will be inferred and you can even call it as

f(Test2, 2)

The result of the function call will be of type Test2

Upvotes: 1

Related Questions