How to get child classes which implement a certain base class using reflection in Type Script?

后端 未结 3 1780
长情又很酷
长情又很酷 2021-01-05 23:37

Can we use reflection in Type Script just like C# to get the list of classes which implement a certain base class?

For example, let say Snake and Horse implement the

3条回答
  •  失恋的感觉
    2021-01-06 00:22

    One way to do it would be to keep track of all the classes you create in one global array:

    var allClasses = []
    function register(c) {
      allClasses.push(c);
    }
    register(class Animal {});
    register(class Snake extends Animal {});
    register(class Horse extends Animal {});
    register(class Car {});
    

    and when you need classes that inherit from particular class just filter out the ones you want:

    Object.values(allClasses).filter((c) => Animal.isPrototypeOf(c))
    

    This solution is not specific to Typescript, it'll work with pure JavaScript too.

提交回复
热议问题