Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing TypeScript modules

Tags:

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)?
like image 437
jax Avatar asked Sep 01 '13 07:09

jax


People also ask

How do I import a TypeScript module?

Use import myFunction from "./myModule" to bring it in. More commonly, TypeScript modules say export myFunction in which case myFunction will be one of the properties on the exported object. Use import { myFunction } from "./myModule" to bring it in.

How do you define a module in TypeScript?

In TypeScript, just as in ECMAScript 2015, any file containing a top-level import or export is considered a module. Conversely, a file without any top-level import or export declarations is treated as a script whose contents are available in the global scope (and therefore to modules as well).


1 Answers

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

like image 115
basarat Avatar answered Nov 15 '22 12:11

basarat