Obtaining A Class Name At Runtime In TypeScript

Feeds

RSS Feed

<< March | April | May >>

Monday, 22nd April 2013

A common question that crops up from time to time on TypeScript forums is how to check the type of a class at runtime using TypeScript.

This can (sort of) be done, although this isn't really comparable to how many other languages work. The technique essentially works by grabbing the code from the class constructor as a string and looking for the name of the function. This works okay for simple situations, but probably won't satisfy your requirements if you have a deep inheritance chain and want all of the data.

class SelfDescribingClass {
    getName() { 
        var funcNameRegex = /function (.{1,})\(/;
        var results = (funcNameRegex).exec((<any> this).constructor.toString());
        return (results && results.length > 1) ? results[1] : "";
    }
}
class Example extends SelfDescribingClass {
}
class AnotherClass extends SelfDescribingClass {
}
var x: SelfDescribingClass = new Example();
var y = new AnotherClass();
var z: AnotherClass = <AnotherClass> x;
alert(x.getName()); // Example
alert(y.getName()); // AnotherClass
alert(z.getName()); // Example

To extend this example, if AnotherClass inherited from Example, it would still answer "Another Class".

Despite it's limitations, this can be a useful technique. You can even have a static Describer to tell you names, rather than having self-describing classes:

class Describer {
    static getName(inputClass) { 
        var funcNameRegex = /function (.{1,})\(/;
        var results = (funcNameRegex).exec((<any> inputClass).constructor.toString());
        return (results && results.length > 1) ? results[1] : "";
    }
}
class Example {
}
class AnotherClass extends Example {
}
var x = new Example();
var y = new AnotherClass();
alert(Describer.getName(x)); // Example
alert(Describer.getName(y)); // AnotherClass

FAQ

Why not use the following?

class Describer {
    static getName(inputClass) { 
        return (<any> inputClass).constructor.name;
    }
}

Because this doesn't work in all the browsers (tested April 2013). The longer version should work in all current browsers.

You Are Here: Home » Blog » Obtaining A Class Name At Runtime In TypeScript