Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript module namespacing in multiple files

Tags:

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?

like image 951
Anders Avatar asked Oct 11 '12 18:10

Anders


1 Answers

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.

like image 131
Valentin Avatar answered Sep 30 '22 17:09

Valentin