Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript decorators, getting constructor argument types and injection

Suppose you have a class like this with the Router decorator attached to it.

@Router
class AuthRouter {

    constructor(private cacheService: CacheService) {}
}

How do I get the constructor parameter types from within the Router decorator? Assume we have stored a singleton of CacheService that we can access if we knew the class name "CacheService".

function Router(target) {

    // somehow get the constructor class name
    const dependencyNames = 'CacheService' // an array if multiple args in constructor

    // getSingleton is a function that will retrieve
    // a singleton of the requested class / object
    return new target(getSingleton(dependencyNames))
}

So whenever we use AuthRouter, it will have CacheService already injected into it.

like image 468
borislemke Avatar asked Mar 16 '26 08:03

borislemke


1 Answers

import 'reflect-metadata'

function Router(target) {
    const types = Reflect.getMetadata('design:paramtypes', target);
    // return a modified constructor
}

Note that you are calling getMetadata with no third param. types will be array of the constructor parameters. types[0].name === 'CacheService' in your case.

like image 151
HandyManDan Avatar answered Mar 18 '26 21:03

HandyManDan