0

I'm learning TypeScript and I know javascript supports metaclass programming, but I can't seem to figure out how to declare a function in TypeScript that runs every time a class is subclassed. I want to build a map of all subclasses by name.

The following is how I'd do it in Python:

from abc import ABCMeta
from typing import Any, Dict, Tuple, Type

subclasses: Dict[str,Type['Base']] = {}

class Meta ( ABCMeta ):
    def __init__ ( cls: Type['Base'], name: str, bases: Tuple[type, ...], nmspc: Dict[Any,Any] ) -> None:
        ABCMeta.__init__ ( cls, name, bases, nmspc )
        if name != 'Base':
            assert name not in subclasses, f'class name {name!r} already defined'
            subclasses[name] = cls

class Base ( metaclass = Meta ):
    pass

class Foo ( Base ):
    pass

class Bar ( Base ):
    pass

print ( repr ( subclasses ) )

Here's an Ruby example of the same concept:

Automatically add a subclass to registry

royce3
  • 1,203
  • 1
  • 10
  • 17
  • Possible duplicate of [ES 6 dynamically work on class after definition](https://stackoverflow.com/questions/45139541/es-6-dynamically-work-on-class-after-definition), and it doesn't look like you can detect when a class is subclassed. – jcalz Jan 12 '20 at 01:46
  • That is indeed the behavior I'm looking for. Disappointing if it's not available. It's a useful feature for implementing DRY. – royce3 Jan 12 '20 at 03:32

0 Answers0