Typescript generic type T toString
Well, Generics in TypeScript is just a construct that helps in typechecking. "T" is in fact "nothing" - it's nothing that can be transpiled into JavaScript. But you need this constructor thing to get your types name. That is why you get that error message. You provided just a type but required is a value (that has that constructor thing) to get your code to work.
Edit:
What you need to do in any case is to provide some JavaScript object. Something like this would work:
class Foo<T> {
test: T;
constructor(value: T) {
this.test = value;
}
getTypeNameOfTest(): string {
return this.test.constructor.name;
}
}
const foo = new Foo<Date>(new Date());
foo.getTypeNameOfTest(); // => "Date"
const baa = new Foo<string>("Howdy");
baa.getTypeNameOfTest(); // => "string"
But here you provide a real JavaScript object instead of just a TypeScript type name. That's why this works.
Using the answer here, I adapted it to better cover my needs, but still, this is not my full answer, because even dough it works, compiles and the tests passes, the following code shows an error in VS and VS Code.
The helper class:
export class TypeHelper {
static typeName(ctor: { name:string }) : string {
return ctor.name;
}
}
The test class (Jasmine spec):
import { TypeHelper } from './../util/TypeHelper';
class MyClass {
public MyGenericMethod<T>(): string {
let iNeedTheTypeNameHere = TypeHelper.typeName(T);
return `Use the string here somehow: ${iNeedTheTypeNameHere}`;
}
}
describe("TypeHelper", () => {
describe("TypeHelper", () => {
it("typeName, returns the string type name of the Class passed as parameter", () => {
let t = TypeHelper.typeName(TypeHelper);
expect(t).toBe("TypeHelper");
let m = TypeHelper.typeName(MyClass);
expect(m).toBe("MyClass");
});
it("typeName, returns the string type name of a generic type T passed as parameter", () => {
let myClass = new MyClass();
let t = myClass.MyGenericMethod<TypeHelper>();
expect(t).toBe("TypeHelper");
let m = myClass.MyGenericMethod<MyClass>();
expect(m).toBe("MyClass");
});
});
});
The error: [ts] 'T' only refers to a type, but is being used as a value here.
I'm not a TS expert but I will keep looking into this to try to understand how to solve this issue.
EDIT: Added playground example