多个文件中的 TypeScript 模块命名空间 [英] TypeScript module namespacing in multiple files

查看:48
本文介绍了多个文件中的 TypeScript 模块命名空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 Typescript 中模仿 C# 的一个特性.

I am trying to mimic a feature of C# in Typescript.

假设我有这个文件夹结构

Let say I have this folder structure

App.ts
Models/
    Person.ts
    Message.ts

然后我在 App.ts 中想要这个:

I then in App.ts want this:

module MyAppNamespace {
    export class ChatApp {
        User: Models.Person;
        constructor () => {
            this.User = new Models.Person("John");
            this.User.Message = new Models.Message("Hello World");
        }
    }
}

我该怎么做?

推荐答案

这是我的建议.我认为您想要做的是定义一个扩展到多个源文件的模块.为此,您需要使用一个内部模块,如下所示:

Here is my suggestion. I think what you want to do is define a module that extends over several source files. To achieve this, you need to use an internal module as follows:

模型/Person.ts

module Model {

  export class Person {
      name: string;
      Message : Message;
      constructor(name: string) {
          this.name = name;
      }   
  }
}

模型/Message.ts

module Model {
   export class Message {
       message: string;
       constructor(message: string) {
          this.message = message;
       }   
   }
}

App.ts

///<reference path='Models/Person.ts'/>
///<reference path='Models/Message.ts'/>
module MyAppNamespace {
    export class ChatApp {
        User: Model.Person;
        constructor () => {
            this.User = new Model.Person("John");
            this.User.Message = new Model.Message("Hello World");
        }   
    }   
}

如果你编译这个

tsc App.ts

那么一切都应该有效.注意模块 outer 是如何在两个源文件中声明的.由于这是一个内部模块,我们必须通过添加///<reference path='foo.ts'/> 声明.

then everything should work. Notice how module outer is declared in two source files. Since this is an internal module, we have to tell the compiler to put them into our scope by adding ///<reference path='foo.ts'/> statements.

这篇关于多个文件中的 TypeScript 模块命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆