在TypeScript中使用外部模块

Ami*_*mid 6 typescript

假设我们在TypeScript中有以下2个外部模块:

export module My.Services.Common 
{
    export class Helper 
    {
       //...
    }
}
Run Code Online (Sandbox Code Playgroud)

export module My.Services 
{
    export class Connection
    {
        //...
    }    
}
Run Code Online (Sandbox Code Playgroud)

现在在我的应用程序中,我想使用Connection和Helper类.我想要实现的类似于C#中的以下代码:

using My.Services;
using My.Services.Common;
Run Code Online (Sandbox Code Playgroud)

或至少只是

using My.Services;
Run Code Online (Sandbox Code Playgroud)

但看起来我无法同时使用Helper和Connection工作.如果我写:

import {My} from './services/common/Helper';
import {My} from './services/Connection;
Run Code Online (Sandbox Code Playgroud)

导致错误"重复标识符'我'".这是合乎逻辑的.所以我的问题是如何从相同(或嵌套)的模块中使用不同的类?

Fen*_*ton 14

我个人对此的看法是脱离你在C#或Java中看到的东西(它更贴近内部模块)并且更像是你正在使用的外部模块......

步骤1.抛弃module关键字.该文件已经是一个模块.

步骤2.导入时提供非点分别名.

步骤3.您现在可以在导入时导入所有内容,"*"或特定类.

./services/common.ts

export class Helper 
{
   //...
}
Run Code Online (Sandbox Code Playgroud)

./services.ts

export class Connection
{
    //...
}
Run Code Online (Sandbox Code Playgroud)

./app.ts

import * as Services from './services'
import { Connection } from './services/common'

var x = new Services.Helper();

var y = new Connection();
Run Code Online (Sandbox Code Playgroud)

您也可以从模块导入多个成员:

import { Connection, Example } from './services/common'

var y = new Connection();

var z = new Example();
Run Code Online (Sandbox Code Playgroud)


Rya*_*ugh 12

为了增加史蒂夫的好答案,因为我已经绘制了ASCII艺术:从这个模块导出的顶级对象My,不与其他名称的文件中的任何其他对象合并My.该My.Services.Common模块唯一实现的目标是使导入更加烦人Helper,因为即使没有其他内容,您也必须完全限定其名称.

你认为你做了什么:

/-My--------------------\
| /-Services---------\  |
| | /-Common---\     |  |
| | | [Helper] |     |  |
| | \----------/     |  |
| |                  |  |
| | [Connection]     |  |
| \------------------/  |
\-----------------------/
Run Code Online (Sandbox Code Playgroud)

你实际做了什么:

/-My---------------\   /-My---------------\ 
| /-Services-----\ |   | /-Services-----\ |
| | /-Common---\ | |   | | [Connection] | |
| | | [Helper] | | |   | \--------------/ |
| | \----------/ | |   \------------------/
| \--------------/ | 
\------------------/
Run Code Online (Sandbox Code Playgroud)

这就好比你家有一个组织系统,你有一打鞋盒,每个里面坐了一个小盒子,每一个内部小盒子.嵌套的盒子没有鞋盒的组织优势!

  • 所有ASCII艺术的额外分数.你甚至做了圆角! (8认同)