简体   繁体   中英

Get typescript generic type as string value

I'm trying to get the name type of a type given in a generic function.

This is for a nodeJS app.

I would like to do something like this:

static Get<T>(): string {
        return typeof T;
    }

But this exemple results as an error: "'T' only refers to a type, but is being used as a value here."

I would like "string" as a result if I call:

let strType: string = Get<string>();

Since generics are not available at run time there is no way to call typeof on that. However you can do it like this

function Get<T>(type: T): string {
        return typeof type;
    }

let strType: string = Get<number>(1);
strType: string = Get<string>("1");

You can adapt this type from the TS Handbook :


type TypeName<T> =
    T extends string ? "string" :
    T extends number ? "number" :
    T extends boolean ? "boolean" :
    T extends undefined ? "undefined" :
    "object";

class Foo {

    static Get<T>(value: T): TypeName<T> {
        return typeof value;
    }
}

Foo.Get(123) // "number"
Foo.Get("str") // "string"

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