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: