23

I am just trying to get my head around TypeScript,

Say I have a module animals.ts like this:

export module Animals {

    export interface Animal {
        name(): void;
    }

    export class Elephant implements Animal {

        constructor() {

        } 

        public name() {
            console.log("Elephant");
        }
    }

    export class Horse implements Animal {

        constructor() {

        }

        public name() {
            console.log("Horse");
        }
    }
}

And I want to use this module in another file animals_panel.ts:

import animals = require("animals")

module AnimalPanel {

    var animal = new animals.Animals.Elephant();
    animal.name();
}
  1. It seems a bit weird to me that I have to use animals.Animals.Elephant(), I would have expected Animals.Elephant(). Am I doing something wrong or is this the correct behaviour?
  2. is it possible to import import animals = require("animals") inside the AnimalPanel module (I get errors when I try to do this)?
jax
  • 37,735
  • 57
  • 182
  • 278
  • 1
    [Documentation for imports](https://github.com/Microsoft/TypeScript-Handbook/blob/master/pages/Namespaces%20and%20Modules.md) – Ondra Žižka Mar 29 '16 at 18:51

2 Answers2

33

When you are using external modules each file is a module. So declaring a local internal module within a file e.g. export module Animals { leads to unnecessary double indirection.

I would code animals.ts as :

export interface Animal {
    name(): void;
}

export class Elephant implements Animal {

    constructor() {

    } 

    public name() {
        console.log("Elephant");
    }
}

export class Horse implements Animal {

    constructor() {

    }

    public name() {
        console.log("Horse");
    }
}

And then use it as :

import animals = require("animals")

module AnimalPanel {

    var animal = new animals.Elephant();
    animal.name();
}

PS: a video on this subject of internal / external typescript modules : http://www.youtube.com/watch?v=KDrWLMUY0R0&hd=1

basarat
  • 261,912
  • 58
  • 460
  • 511
  • 2
    I saw in angular they imported a module (let's say `NgModule)` then they said `@NgModule({})`. What does it mean? I mean the `@NgModule` (Thanks a lot) – Mohammad Kermani May 30 '17 at 12:04
2

You can use 2 types of syntaxes export/import:

  1. (AMD style) Require syntax which supported in ES5:

    var animals = require("animals");

  2. Use import style which started suppurts from ES6:

    import { Elephant, Horse } from "animals";

TypeScript supports export = to model the traditional CommonJS and AMD workflow. So both variants will works and I suggest to use 2nd because it more powerful mechanism.

More details about it can be found on official the TypeScript Modules web page.

Alex Filatov
  • 2,232
  • 3
  • 32
  • 39