24

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

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

How would I do this?

1 Answer 1

34

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Works good in Visual studio too. Would it be possible to only have to import one of these files? In VS you normally use /// <reference path="_allRefs.js"/>. Would this be possible? E.g: <reference path="AllModels.ts"/>?
For future reference, this is possible. So you could create one file "allModels.ts" that contains the /// refs.
why store Person and Message in separate files? Could I have a Model.ts file with just the class definitions without being wrapped in a module? If so how would I import these definitions in App.ts..
UPDATE: Typescript 0.9.5 now have support for _referenes.ts (blogs.msdn.com/b/typescript/archive/2013/12/05/…)
Since Typescript 1.5 "internal modules" are now "namespaces". In this example module Model should now be namespace Model.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.