使用编译器选项生成d.ts文件会生成角度误差

时间:2016-09-30 13:23:33

标签: angularjs typescript

使用tsc编译器选项"declaration": true时出现以下错误:

error TS4019: Implements clause of exported class 'MyClass' has or is using private name 'angular'.

使用"declaration": false时,我没有收到错误。

使用 TypeScript版本: 2.0.3

示例代码

MyClass.ts

/// <reference path="node_modules/@types/angular/index.d.ts" />
module MyModule {
    export class MyClass implements angular.IServiceProvider {
        constructor() {
        }
        $get;
    }
}

tsconfig.json

{
  "compilerOptions": {
  "noImplicitAny": false,
  "noEmitOnError": true,
  "removeComments": false,
  "sourceMap": true,
  "target": "es5",
  "declaration": true
},
"exclude": [
  "node_modules"
]
}

https://github.com/iwhp/issues/tree/master/typescript-bug-declaration-file-with-angular

上有一个github回购

预期行为:

应创建.d.ts文件。

添加上面的示例

我添加了以下类,以显示此处使用了MyClass.ts。

MyClass2.ts

/// <reference path="node_modules/@types/angular/index.d.ts" />
module MyModule {
    export class MyClassB implements angular.IServiceProvider {
        constructor(myClass: MyModule.MyClass) {
        }
        $get;
    }
}

1 个答案:

答案 0 :(得分:1)

如果您总是要使用typescript 2.0进行编译,则可以替换此行

/// <reference path="node_modules/@types/angular/index.d.ts" />

更现代的

import * as angular from 'angular';

然后创建了.d.ts文件,但它是空的,因为你没有导出MyModule - 你也需要export

export module MyModule {

更新

现在,如果你想将模块MyModule拆分成几个文件,我找不到任何方法来引用角度类型定义,同时保持模块MyModule内部。关于angular私有的这个错误消息看起来像一个错误 - 在angular.d.ts标识符angular中被多次声明,其中一些声明是export所以我不知道为什么它被认为是私人的。

如果您想要将模块设置为外部路线,那么您可以使用此answer中描述的解决方法 - 您需要在其源文件中将MyClass和MyClassB置于顶层,并具有单独的MyModule将它们重新导出的文件。

缺点是:

  • 如果不将模块类型更改为amdsystem,则无法编译为单个文件,因此您必须将"module": "amd", "moduleResolution": "node"添加到tsconfig.json编译(编译为单独的文件不受影响)

  • MyClass和MyClassB仍然在顶级以及MyModule模块中导出(如果需要,可以将它们移动到子目录中)

  • MyClassB和MyModule之间存在循环引用(不是真正的缺点,节点模块解析应该处理得很好,但看起来很奇怪)。

完整档案:

<强> MyClass.ts

import * as angular from 'angular';

export class MyClass implements angular.IServiceProvider {
    constructor() {
    }

    $get;
}

<强> MyClassB.ts

import * as angular from 'angular';
import * as MyModule from './MyModule';

export class MyClassB implements angular.IServiceProvider {
    constructor(myClass: MyModule.MyClass) {
    }

    $get;
}

MyModule.ts

export {MyClass} from './MyClass';
export {MyClassB} from './MyClassB';
相关问题