Angular - VS2015中的类型错误中不存在'$ inject'属性

问题描述 投票:1回答:1

当我将AngularJS项目升级到Angular 4时,我在Visual Studio 2015中遇到了数千个编译器错误。我已经将应用程序转换为可以成功运行AngularJS代码和Angular4代码的混合应用程序。使用CLI编译,打字稿编译成功,应用程序正常工作。

大多数错误都在* .d.ts文件中,但* .ts文件中也存在一些错误。我想知道* .ts中的错误是否阻止了正确的编译,以及是否导致了* .d.ts文件中的其他错误。

当我有类似的东西(使用AngularJS代码)时,其中一个错误类型出现在* .ts文件中:

myCtrl.$inject = ['$window'];

我收到此错误:

Property '$inject' does not exist on type 'typeof myCtrl'

假设我需要修复此特定错误(并且这不仅仅是导致$ inject无法识别的其他编译问题),我还需要做什么?这是我的一个* .ts文件的完整代码,其中包含错误:

(function() {

class myCtrl {

    window: any;

    constructor($window, $location) {
        this.window = $window;
    }

    myMethod(myParameter) {
        ... do stuff
    }
}

// *****error on this line*******
myCtrl.$inject = ['$window'];

class myDirective {

    restrict: string;
    controller: string;
    controllerAs: string;
    templateUrl: string;
    $document: any;
    $window: any;
    instance: any;

    constructor($document, $window) {
        this.restrict       = 'E';
        this.controller     = 'myCtrl';
        this.controllerAs   = 'myCtrlAlias';
        this.templateUrl    = '/yadda.html';
        this.$document      = $document;
        this.$window        = $window;
    }
    static myFactory($document, $window) {
        var instance = new myDirective($document, $window);
        return instance;
    }
}

angular
    .module('myModule', ['myDependency'])
    .directive('mainNav', ['$document', '$window', myDirective.myFactory])
    .controller('myCtrl', myCtrl);
})();

这是我的tsconfig.json。我正在使用tsc 1.8

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [ "es2015", "dom" ],
    "noImplicitAny": false,
    "suppressImplicitAnyIndexErrors": true,
    "noStrictGenericChecks": true
  },
  "include": [ "**/*.ts" ],
  "exclude": [
    "node_modules"
  ]
}
angularjs typescript dependency-injection
1个回答
1
投票

直接分配类static和prototype属性会导致TypeScript中的类型错误,因为存在一些限制

TypeScript本身就支持类字段。它应该是:

class myCtrl {
    static $inject = ['$window'];

    constructor($window, $location) { ... }
    ...
}

这也允许在构造函数的正上方进行DI注释并避免DI错误。

© www.soinside.com 2019 - 2024. All rights reserved.