4

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>();
3
  • What is the purpose of that function? Commented Jul 1, 2019 at 13:18
  • The answer you've accepted gives you just a string whereas my answer gives you the exact literal string type e.g. number, object etc Commented Jul 1, 2019 at 13:34
  • The answer I've accepted tells that: "Since generics are not available at run time ", that is te answer of my question. Your answer is useful to bypass my problem. Thanks for that :) Commented Jul 1, 2019 at 14:36

2 Answers 2

5

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"

Sign up to request clarification or add additional context in comments.

Comments

2

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

4 Comments

or just simply Get(1), Get("1") (type inference)
@Ric Sure, at that point you can also simply call typeof 1.
Yep absolutely, not sure what the use case of this actually is, but this is the answer
You've explained the misconception correctly and concisely, but you should probably replace T with a non generic type string | number | boolean | null | undefined in your solution. Otherwise, the function may perpetuate the misconception in the OP.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.