Get Off My Lawn Get Off My Lawn - 3 months ago 9
TypeScript Question

Create instance of all classes that extend a base class

I have a base class called

Editor
, I then have items that will extend that class. Is it possible for me to create an instance of all those classes that extend
Editor
without manually creating them all?

class Editor<T> {

}

class TransformEditor extends Editor<Transform> {

}

class SomethingEditor extends Editor<Something> {

}


So, in this example the code doesn't know
TransformEditor
exits, but it is in the codebase, so is it possible to do something where I can get a list of these items, then create an instance of each?

Answer

So there's no way to do this at runtime with TypeScript without adding additional code since there's no way to do this with JavaScript.

You could use TypeScript's decorators to track the children. Here's an extremely simple example:

class Editor {}

const children = []; // This could be an object that maps parents to children

function TrackChild(constructor: Function) {
  // You could also add more fancy prototype/constructor shenanigans here
  children.push(constructor);
}

@TrackChild 
class TransformEditor extends Editor {}

@TrackChild
class SomethingEditor extends Editor {}

console.log(children);

This decorator could of course become much more sophisticated. Here's a very detailed example of tracking a full genealogy with decorators