TypeScript module namespacing in multiple files

前端 未结 1 1281
隐瞒了意图╮
隐瞒了意图╮ 2020-12-14 07:59

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
相关标签:
1条回答
  • 2020-12-14 08:18

    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:

    Models/Person.ts

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

    Models/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");
            }   
        }   
    }
    

    If you compile this with

    tsc App.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.

    0 讨论(0)
提交回复
热议问题