I am reading this article https://nehalist.io/dependency-injection-in-typescript/ and studying the example project https://github.com/nehalist/di-ts, this is what I have learnt.
Decorator is the key for the codes to work. See https://www.typescriptlang.org/docs/handbook/decorators.html
Decorator is currently still an experimental feature in typescript, stage 2 proposal for JS. To enable decorator, set "experimentalDecorators" to true in typescript configuration.
Defined an interface Type<T> which represents a class that can be instantiated to obtain an object of type T (the class).
GenericClassDecorator<T> is just a function that receives a Type<T> (not T, which is an instance of T)
/**
* Type for what object is instances of
*/
export interface Type<T> {
new(...args: any[]): T;
}
/**
* Generic `ClassDecorator` type
*/
export type GenericClassDecorator<T> = (target: T) => void;
Here 'Service' is in fact a "decorator factory" that returns a GenericClassDecorator<Type<any>>, which is a function that receives a target that will be decorated.
/**
* @returns {GenericClassDecorator<Type<any>>}
* @constructor
*/
export const Service = () : GenericClassDecorator<Type<any>> => {
return (target: Type<any>) => {
// do something with `target`, e.g. some kind of validation or passing it to the Injector and store them
};
};