如何在typescript中创建导入类对象?

时间:2014-03-10 08:24:23

标签: typescript amd

interface IModal {
    widgetNames: KnockoutObservableArray<string>;
    widgets: KnockoutObservableArray<IWidget>;
}

一个web.d.ts文件,其中我声明了模块

declare module "modules/dialog/modal" {
    var theModal: IModal;
    export = theModal;
}

class modal implements IModal {
   widgetNames: KnockoutObservableArray<string>;
   widgets: KnockoutObservableArray<IWidget>;

 constructor() {
    this.widgetNames= ko.observable<string>(['widget1','widget2'])
 }
}
export = modal; 

类索引是我想导入modal.ts文件并创建新对象的地方。 我的问题是,当导入modal.ts然后无法创建对象。 Typescript不是编译器index.ts文件这里“new modal()”

import modal = require('modules/dialog/modal');
class index{
constructor(){
  var_modal = new modal();//problem here, unable to create modal. not compiled by typescript compiler; i don't want to use singleton pattern;

 }
}
export = index;

解决方案导入:这工作正常

import modal = require('./modal');//modal path
class index{
constructor(){
  var_modal = new modal();

 }
}
export = index

这项工作很好,但如果我想改变('./modal')路径:“../../ widgets/personInfo/viewmodel” 在重建解决方案之后,visual studio拍摄了一个错误:

无法解析外部模块“../../widgets/personInfo/viewmodel” 构建:模块不能别名为非模块类型。 “新”表达式无效

1 个答案:

答案 0 :(得分:2)

你不应该:

declare module "modules/dialog/modal" {
    var theModal: IModal;
    export = theModal;
}

如果您有fooModal.ts文件:

class modal implements IModal {
   widgetNames: KnockoutObservableArray<string>;
   widgets: KnockoutObservableArray<IWidget>;

 constructor() {
    this.widgetNames= ko.observable<string>(['widget1','widget2'])
 }
}
export = modal; 

您可以这样做:

import modal = require('./fooModal');
class index{
constructor(){
  var_modal = new modal();//problem here, unable to create modal. not compiled; i don't want to use singleton pattern;

 }
}
export = index;