0

我几乎完全复制了 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;
        ...
    }
}
4

2 回答 2

3

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

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

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

    constructor(@Inject("IDatabase") db : IDatabase)
    {
        this.db = db;
        ...
    }
}
于 2016-02-02T10:45:20.203 回答
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;
    }
}
于 2016-02-02T15:00:31.913 回答