Here is the definition of my function:
getData<T extends Entity> () { }
I don't currently accept any arguments. Is there a way for me to translate the T into the string name of the type at runtime? Perhaps using typeof?
I am from the C# world where you would use reflection. However I am new to Javascript and not sure what the equivalent would be.
Thanks.
Use the IsGenericType property to determine whether the type is generic, and use the IsGenericTypeDefinition property to determine whether the type is a generic type definition. Get an array that contains the generic type arguments, using the GetGenericArguments method.
Basically if you do class Foo implements List<Integer> then you can get the generic type. Doing something like List<Integer> foo; you cannot because of type erasure. Not all generic types are erased.
TypeScript Generics is a tool which provides a way to create reusable components. It creates a component that can work with a variety of data types rather than a single data type. It allows users to consume these components and use their own types.
To specify generic object type in TypeScript, we can use the Record type. const myObj: Record<string, any> = { //... }; to set myObj to the Record type with string keys and any type for the property values.
Types are erased during compilation, so no. You should never ever have a generic function that doesn't use its type parameter in an argument position.
Assuming getData
works on classes, you could write something like:
class NotSureThisIsReallyAGoodIdea {
static getData<T>(cls: new(...args: any[]) => T): T {
/* magic happens */
const url = 'http://example.com/' + cls['name'];
return <T>undefined;
}
}
class SomeShape {
x: number;
}
let s = NotSureThisIsReallyAGoodIdea.getData(SomeShape);
s.x; // OK
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