How to create an object instance of a typescript class from within plain js using AMD modules

StackOverflow https://stackoverflow.com/questions/23685844

Вопрос

Lets say I have the following file tests.ts:

module tests {

    export class Greeter
    {
        sayHello() {
            console.log("hello world");
        }
    }
}

And compiling it as and AMD module. How exactly do I create an object instance of Greeter in a regular JavaScript (not typescript!) file?

I was thinking of something like:

require(['tests', function(tests) {
    var greeter = new tests.Greeter();
    greeter.sayHello();
}

but that doesn't seem to work - the debugger shows me tests is of __proto__ but I can't find a member 'Greeter' in it.

Это было полезно?

Решение

You've forgotten the export keyword on the top-level module, so that top code block doesn't actually export anything visible as an external module.

Also, refer to the Modules in TypeScript "Needless Namespacing" pitfall:

If you're converting a program from internal modules to external modules, it can be easy to end up with a file that looks like this:

shapes.ts

 export module Shapes {
     export class Triangle { /* ... */ }
     export class Square { /* ... */ } }
 }

The top-level module here Shapes wraps up Triangle and Square for no reason. This is confusing and annoying for consumers of your module:

shapeConsumer.ts

 import shapes = require('./shapes'); var t = new
 shapes.Shapes.Triangle(); // shapes.Shapes?

A key feature of external modules in TypeScript is that two different external modules will never contribute names to the same scope. Because the consumer of an external module decides what name to assign it, there's no need to proactively wrap up the exported symbols in a namespace.

To reiterate why you shouldn't try to namespace your external module contents, the general idea of namespacing is to provide logical grouping of constructs and to prevent name collisions. Because the external module file itself is already a logical grouping, and its top-level name is defined by the code that imports it, it's unnecessary to use an additional module layer for exported objects.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top