view raw
Get Off My Lawn Get Off My Lawn - 9 months ago 32
TypeScript Question

Create instance of all classes that extend a base class

I have a base class called

, I then have items that will extend that class. Is it possible for me to create an instance of all those classes that extend
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
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?


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

class TransformEditor extends Editor {}

class SomethingEditor extends Editor {}


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