首页 文章

如何在单独文件中的命名模块中使用类?引发ReferenceError:未定义模块

提问于
浏览
0

我正在尝试使用TypeScript ECMAScript6使用Visual Studio 2015社区版创建一个简单的Node.js控制台应用程序,并且无法使用app.ts中模块内定义的类 . 然而,Visual Studio会将模块“DataModels”显示为名称空间,也会显示intellisense中的类,但在app.ts中初始化时会抛出错误

错误:ReferenceError:未定义DataModels

尝试使用AMD和CommonJs作为模块系统的VS项目设置,但没有运气 .

文件夹结构

/
 app.ts
 DataModels.ts
 Scripts
  Typings (dir)
   Node   (dir)
    node.d.ts

app.ts

/// <reference path="DataModels.ts" />
var user: IUser = new DataModels.User();
user.Name = 'user1';
console.log(user.Name);

DataModels.ts

interface IUser {
    Name: string;
    Email: string;
    UserName: string;
    Password: string;
    ProfilePicPath: URL;

}

module DataModels {

    export class User implements IUser {
        private _name: string;
        private _email: string;
        private _username: string;
        private _password: string;
        private _profilePicPath: URL;

        public get Name() {
            return this._name;
        }
        public set Name(value) {
            this._name = value;
        }

        public get Email() {
            return this._email;
        }
        public set Email(value) {
            this._email = value;
        }

        public get UserName() {
            return this._username;
        }
        public set UserName(value) {
            this._username = value;
        }

        public get Password() {
            return this._password;
        }
        public set Password(value) {
            this._password = value;
        }

        public get ProfilePicPath() {
            return this._profilePicPath;
        }
        public set ProfilePicPath(value) {
            this._profilePicPath = value;
        }
    }
}

1 回答

  • 1

    尝试使用AMD和CommonJs作为模块系统的VS项目设置,但没有运气 .

    您的代码不能与任何模块系统一起使用,因为它不是以外部模块格式编写的,只有在将项目编译为单个文件时才能使用 . 现在,假设您确实想要使用某种类型的模块系统,那么您应该如何编写代码以使用AMD / CommonJS等:

    app.ts

    // note the lack of reference paths
    import * as DataModels from './DataModels';
    
    var user: DataModels.IUser = new DataModels.User();
    user.Name = 'user1';
    console.log(user.Name);
    

    DataModels.ts

    export interface IUser {
      ...
    }
    
    export class User implements IUser {
      ...
    }
    

相关问题