为什么Typescript不能编译这个InversifyJS装饰器?

时间:2016-02-02 09:29:17

标签: typescript inversifyjs

我几乎完全复制Inversify文档(版本1.2.2)并且无法编译,给我的Typescript错误TS1238。为什么呢?

'use strict';
import './tools/typescriptImports';
import IServer = require('./iServer.ts');
import IDatabase = require('../database/iDatabase');
import express = require('express');
import bodyParser = require('body-parser');
import config = require('../config');
import types = require('../tools/types.ts');
import _ = require('lodash');
import async_ = require('async');
import { Inject } from "inversify";

@Inject("IDatabase") // <- error TS1238: Unable to resolve signature of class decorator when called as an expression. Supplied parameters do not match any signature of call target.
class Server implements IServer
{
    db : IDatabase;
    expressApp : express.Express;

    constructor(db : IDatabase)
    {
        this.db = db;
        ...
    }
}

2 个答案:

答案 0 :(得分:3)

查看source code,Inject绝不可能是类装饰器。类装饰器应该返回一个构造函数,但是Inject返回的装饰器返回void(Inject是一个装饰器工厂,它返回装饰器函数本身。)

Inject实际上返回一个参数装饰器,并且 - 顾名思义 - 应该用于装饰方法参数:

class Server implements IServer
{
    db : IDatabase;
    expressApp : express.Express;

    constructor(@Inject("IDatabase") db : IDatabase)
    {
        this.db = db;
        ...
    }
}

答案 1 :(得分:2)

我们只发布InversifyJS版本1.3.0,它允许您将Inject装饰器应用于类:

interface IKatana {
    power : number;
    hit() : boolean;
}

interface IShuriken {
    power : number;
    throw() : boolean;
}

@Inject("IKatana", "IShuriken")
class Warrior {

    private _katana : IKatana;
    private _shuriken : IShuriken;

    constructor(katana : IKatana, shuriken : IShuriken) {
        this._katana = katana;
        this._shuriken = shuriken;
    }
}

不再支持以下内容:

class Warrior {

    private _katana : IKatana;
    private _shuriken : IShuriken;

    constructor(
        @Inject("IKatana") katana : IKatana, 
        @Inject("IShuriken") shuriken : IShuriken
    ) {
        this._katana = katana;
        this._shuriken = shuriken;
    }
}

不再支持基于命名约定的注入:

class Warrior {

    private _katana : IKatana;
    private _shuriken : IShuriken;

    constructor(IKatana: IKatana, IShuriken: IShuriken) {
        this._katana = IKatana;
        this._shuriken = IShuriken;
    }
}