多个文件中的 TypeScript 模块命名空间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12845810/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 16:15:05  来源:igfitidea点击:

TypeScript module namespacing in multiple files

typescript

提问by Anders

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

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

Let say I have this folder structure

假设我有这个文件夹结构

App.ts
Models/
    Person.ts
    Message.ts

I then in App.tswant this:

然后我App.ts想要这个:

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

How would I do this?

我该怎么做?

回答by Valentin

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 internalmodule as follows:

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

Models/Person.ts

模型/人.ts

module Model {

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

Models/Message.ts

模型/消息.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");
        }   
    }   
}

If you compile this with

如果你编译这个

tsc App.ts

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

那么一切都应该有效。注意模块outer是如何在两个源文件中声明的。由于这是一个内部模块,我们必须通过添加///<reference path='foo.ts'/>语句来告诉编译器将它们放入我们的作用域中。