Skip to content

TypeScript interfaces for Dependency Injection #3060

Closed
@pavelsavara

Description

@pavelsavara

I tried to imagine how could I use new Decorator Metadata in order to autowire dependency injection with TS interfaces. Test with tsc 1.5 beta gives me Object constructor instead of interface constructor (perhaps obviously), but that limits the ability of DI container to wire the dependency by type of the interface (as is usual in C#).

This would be the sample.

///<reference path="node_modules\reflect-metadata\reflect-metadata.d.ts"/>

import "reflect-metadata";

export interface IEngine{
}

export class Engine implements IEngine {
}

export class TestEngine implements IEngine {
}

function Inject() {
  return function (target: Function) {
  }
}

@Inject()
export class Car {
  constructor(public engine: IEngine) {}
}

tcs 1.5beta compiles to this

var Car = (function () {
    function Car(engine) {
        this.engine = engine;
    }
    Car = __decorate([
        Inject(), 
        __metadata('design:paramtypes', [Object])
    ], Car);
    return Car;
})();

Ideally the line should be

        __metadata('design:paramtypes', [IEngine])

and IEngine could be dummy class/constructor.

Or it could be string full name of the interface type

        __metadata('design:paramtypes', 'IEngine')

I tried to explain this to Angular team before here
angular/angular#135

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions