简体   繁体   English

导入TypeScript名称空间(如在C#/ .NET中)

[英]Import TypeScript namespaces (as in C#/.NET)

In my TypeScript project I use classes and interfaces spread across several files structured in namespaces. 在我的TypeScript项目中,我使用分布在命名空间中的几个文件的类和接口。 Just as I use to do it in C#/.NET. 正如我在C#/ .NET中使用它一样。


IDispatcher.ts : IDispatcher.ts

namespace Dispatcher {
    export interface IDispatcher {
        Dispatch(msg: string): Promise<string>;
    }
}

DispatcherImpl.ts : DispatcherImpl.ts

namespace Dispatcher {
    export class Dispatcher implements Dispatcher.IDispatcher {
        Dispatch(msg: string): Promise<string> {
            return new Promise<string>((resolve, reject) => {
                    resolve('result');
            });
        }
    }
}

Test.ts : Test.ts

namespace Test {
    export class Test {
        private dispatcher: Dispatcher.IDispatcher;

        constructor() {
            this.dispatcher = new Dispatcher.Dispatcher();
        }
    }
}

let testRun = new Test.Test();

Everything compiles fine to JavaScript (using target and module = es6 ). 一切都编译好JavaScript(使用targetmodule = es6 )。
But when I run node test.js I get the error 但是当我运行node test.js我得到了错误

this.dispatcher = new Dispatcher.Dispatcher();
                      ^
ReferenceError: Dispatcher is not defined

When I try to import DispatcherImpl it states that File 'DispatcherImpl.ts' is not a module . 当我尝试import DispatcherImpl它声明File 'DispatcherImpl.ts' is not a module And with require('DispatcherImpl.ts') it just resolves to any and does not work as expected either. 并且使用require('DispatcherImpl.ts')它只会解析为any并且也不会按预期工作。

So I expect TypeScript namespaces to behave similar to .NET namespaces. 所以我希望TypeScript命名空间的行为类似于.NET命名空间。 But that does not seem to be the case at all. 但事实似乎并非如此。 How is the proper way to arrange my interfaces and classes and how do other classes use/import them? 如何安排我的接口和类以及其他类如何使用/导入它们? Maybe there is a way to make the TypeScript compiler resolve the namespaces automatically? 也许有一种方法可以让TypeScript编译器自动解析名称空间?

Currently there is no include oder import statement for namespaces in TypeScript. 目前 ,TypeScript中没有include名称空间的oder import语句。

I found a workaround using the outFile option in tsconfig.json : 我在tsconfig.json中找到了使用outFile选项的解决方法:

"outFile": "test.js"

This way all TypeScript code gets translated into one single JavaScript-file. 这样,所有TypeScript代码都会被翻译成一个单独的JavaScript文件。
To be arranged in the correct order every TypeScript file has to define its dependencies by eg 要按正确的顺序排列,每个TypeScript文件必须通过例如定义其依赖关系

/// <reference path="DataModel/Common.ts" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM