lundi 1 août 2016

TypeScript / JavaScript: How to scan for all classes (and filter by super class)?

1) In TypeScript, how can I find all defined classes?
2) How can I filter them by super class?

I have model classes, which extend FrameModel. These are not known before runtime (pluggable).
So I want to get a list of subclasses of FrameModel.

This is my attempt:

public static scan()
{
    this.mapping = {};
    for (var key in Object.keys(window)){
        var val = window[key];
        if (val == null)
            continue;
        if (typeof val !== 'object')
            continue;
        if (val.constructor !== Function) // Not quite sure about this
            continue;
        if (val.constructor.prototype !== FrameModel) // Neither
            continue;
        this.mapping[key] == val; // Doesn't work
    }
}

What I consider problematic is:

  1. The use of window - let's say it won't run in the browser. Then I need a global object in general. I've seen using this in some context, IIRC in a function which is called outside an object, to get the global object. Is that the "official" way?

  2. window[key] doesn't work - Window is not assignable to typeof FrameModel

  3. It scans all props of Window, not just Functions. I assume there's some smarter way to get a list of Functions.

TypeScript 1.8. Playground





Aucun commentaire:

Enregistrer un commentaire