Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to get the name of the generic type in a generic (<T>) function/class (Typescript)?

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.

like image 756
Aneela Brister Avatar asked Apr 11 '16 19:04

Aneela Brister


People also ask

How do you identify a generic type?

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.

How do I find my generic class name?

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.

What is generic type T in TypeScript?

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.

How would you define generic type for objects in TypeScript?

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.


1 Answers

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
like image 87
Ryan Cavanaugh Avatar answered Oct 19 '22 09:10

Ryan Cavanaugh