Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// Annotations can be put on:
// - functions / classes
// - function parameters
@Foo('bar')
function foo(@Baz() param1, @Baz() param2: Foo) {}
// GETS TRANSPILED INTO:
function foo() {}
// Using property getters, so that it works with circular references.
Object.defineProperty(foo, 'annotations', {get: function() {
return [new Foo('bar')];
}});
Object.defineProperty(foo, "parameters", {get: function() {
return [
[new Baz], // annotations on param1
[Foo, new Baz] // annotations on param2
];
}});
// An example of Dependency Injection using the annotations in runtime.
class Engine {}
class Car {
constructor(engine: Engine) {}
}
var injector = new Injector();
var car = injector.get(Car);
// This is roughly what happens inside the `injector.get(Car)` call.
// - do I have an instance of Car (check a cache/map)?
// - if yes, return
// - if not, instantiate:
// - check Car.parameters annotations and instantiate the dependencies first:
// - var dep1 = injector.get(Car.parameters[0][0]);
// - return new Car(... already instantiated deps ...)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment