GeJN
GeJN

Reputation: 69

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>();

Upvotes: 4

Views: 12686

Answers (2)

Nurbol Alpysbayev
Nurbol Alpysbayev

Reputation: 21851

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"

Upvotes: 5

Murat Karag&#246;z
Murat Karag&#246;z

Reputation: 37584

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");

Upvotes: 2

Related Questions