使用TypeScript 2名稱空間,我如何獲取代碼以識別添加到子文件夾中名稱空間的類。TypeScript 2.0:如何在同一個命名空間中引用對象,但在子文件夾中引用對象?
(我使用AngularJS 1.5和的WebPack,但既不這些應發揮在此的一部分。)
在下面的例子中,指令D1是下指示一個文件夾中,並且可以_bootstrap_directives.ts沒有解決它。它得到這個錯誤:
錯誤TS2339:'typeof指令'類型中不存在屬性'D1Directive'。
也許我只需要創建myLibrary.d.ts來顯式定義合同?
-
directives
> d1
> d1.directive.ts
> d1.scss
> _bootstrap_directives.ts
> d2.directive.ts
-
> d1.directive.ts (d2.directive is the same with a different class name and no scss import)
import './d1.scss'; // for webpack
namespace MyLibrary.Directives {
export class D1Directive implements ng.IDirective {
restrict: string = 'A';
scope: boolean = false;
constructor() {
// noop
}
static factory(): ng.IDirectiveFactory {
const directive =() => {
return new D1Directive();
}
return directive;
}
}
}
-
> _bootstrap_directives.ts (
// Property 'D1Directive' does not exist on type 'typeof Directives'.
import './d1/d1.directive'; // for webpack
angular.module('myLibrary')
.directive('d1', MyLibrary.Directives.D1Directive.factory());
// This one works
import './d2.directive'; // for webpack
angular.module('myLibrary')
.directive('d2', MyLibrary.Directives.D2Directive.factory());
我使用Visual Studio 2015年
一般的教訓是避免命名空間(內部模塊)。命名空間是一個概念,在明確表示JavaScript將轉移到具有ES6的適當模塊系統之前,已經引入了這個概念。現在,你應該[只使用模塊](https://www.typescriptlang.org/docs/handbook/modules.html)(即TypeScript中的「外部模塊」) – poke
我實際上已經切換到使用模塊而不是命名空間。不幸的是,發生完全相同的問題。模塊Library.Blah.Blah上方的導入語句會導致TS編譯器找不到導出的類。即使該.ts文件位於同一個文件夾中。 –
我不會說webpack是問題。我會說頂部的導入是問題(TypeScript)。我意識到這篇文章有點舊了,但是我一直在爲這個上週做鬥爭。查看我的答案瞭解更多信息。 –