Aneela Brister
Aneela Brister

Reputation: 101

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.

Upvotes: 8

Views: 2278

Answers (1)

Ryan Cavanaugh
Ryan Cavanaugh

Reputation: 220994

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

Upvotes: 5

Related Questions