Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get typescript generic type as string value

Tags:

typescript

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>();
like image 851
GeJN Avatar asked Sep 11 '25 13:09

GeJN


1 Answers

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"

like image 68
Nurbol Alpysbayev Avatar answered Sep 14 '25 03:09

Nurbol Alpysbayev