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>();
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With