简体   繁体   中英

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?

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.

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