Bob.Yang
Bob.Yang

Reputation: 51

How to get Generic Parameter Type of class in Typescript

I want to get the type of Generic Parameter for some class, such as:

class ClassA<T> {
    value!: T;

    getParameterType()  {
        return <type of T>;
    }
}

the getParameterType method return the Class Type of T, and how to do it ? or has other methods?

Upvotes: 1

Views: 5423

Answers (1)

user11534547
user11534547

Reputation:

You can't return a type in Typescript, since a type is not a value. Typescript compiles to Javascript so types don't exist there. The error you get when I compile your code(when I concatenate the 'type' and 'of' into typeof) says:

'T' only refers to a type, but is being used as a value here.

and that's completly correct, you can only return values and use these values to perform operations on. You can't return a type. This is the same thing as writing the following function:

function wrong() {
    return string // You can return 'hello world'
}

You can't say return string

Also look what happens with your typescript code when you compile it:

let x: string = 'hello world' becomes in Javascript let x = 'hello world' The types are gone!

Solution

What you are looking for is a type to extract the generic parameter T from the ClassA, typescript has keyword infer wich allows you get the to get the type parameters of any type.

type getType<T> = T extends ClassA<infer U> ? U : never

and use it like this:

type Test = getType<ClassA<string>> the type of Test is string

NOTE:

Pay attention to to difference in types and values, they are not the same things and are treated completely different.

Upvotes: 6

Related Questions