Skip to content

Instantly share code, notes, and snippets.

@vojtajina
Created November 26, 2014 22:26
Show Gist options
  • Save vojtajina/516199b89c7b38d71412 to your computer and use it in GitHub Desktop.
Save vojtajina/516199b89c7b38d71412 to your computer and use it in GitHub Desktop.
// 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