zeroin zeroin - 4 months ago 13
TypeScript Question

Get list of extended classes in TypeScript

I have:

classA
classB extends ClassA
classC extends ClassB


I created object on classC:

var myClassC= new classC();


ClassA has this method:

public get className(): string {
var funcNameRegex = /function (.{1,})\(/;
var results = (funcNameRegex).exec(this["constructor"].toString());
return (results && results.length > 1) ? results[1] : "";
}


Which returns "ClassC" string if I call myClassC.getClassName();

What I need is to get a list of all classes up to the base class: ClassC, ClassB, ClassA. Is there a way to do this?

Answer

Yeah, that is indeed possible:

function getClassName(obj: any): string {
    var funcNameRegex = /function (.{1,})\(/;
    var results = (funcNameRegex).exec(obj.constructor.toString());
    return (results && results.length > 1) ? results[1] : "";
}

class ClassA {
    public get className(): string[] {
        let classNames = [];
        let obj = Object.getPrototypeOf(this);
        let className: string;

        while ((className = getClassName(obj)) !== "Object") {
            classNames.push(className);
            obj = Object.getPrototypeOf(obj);
        }

        return classNames;
    }
}

class ClassB extends ClassA {}

class ClassC extends ClassB {}

let a = new ClassA();
console.log(a.className); // ["ClassA"]

let b = new ClassB();
console.log(b.className); // ["ClassB", "ClassA"]

let c = new ClassC();
console.log(c.className); // ["ClassC", "ClassB", "ClassA"]

(code in playground)