typescript - 如何在 TypeScript 中通过导入使用命名空间

标签 typescript namespaces es6-modules

我在两个单独的文件中有两个类,一个从另一个扩展。基类包含一些使用节点模块的 import 语句。我不清楚为什么派生类(在单独的文件中)不能识别基类!!!???

有人可以澄清一下吗?

// UtilBase.ts

/// <reference path="../typings/node.d.ts" />
/// <reference path="../typings/packages.d.ts" />

import * as path from "path"; // <---- THIS LINE BREAKS THE BUILD!!!!

namespace My.utils {

    export class UtilBase {

        protected fixPath(value: string): string {
            return value.replace('/', path.sep);
        }
   }
}

然后

// UtilOne.ts
/// <reference path="UtilBase.ts" />

namespace My.utils {

    export class UtilOne extends My.utils.UtilBase {

    }
}

编译后得到:

src/UtilOne.ts(6,47): error TS2339: Property 'UtilBase' does not 
exist on type 'typeof utils'

最佳答案

命名空间的解决方案(不推荐)

要解决您的问题,您可以导出您的命名空间:

// UtilBase.ts
import * as path from "path";
export namespace My.utils {
    export class UtilBase {
        protected fixPath(value: string): string {
            return value.replace('/', path.sep);
        }
   }
}

然后,您应该能够导入它:

// UtilOne.ts
import {My} from './UtilBase';
namespace My.utils {
    export class UtilOne extends My.utils.UtilBase {
    }
}

但是,如果目的是整理代码,it is a bad practice to use namespaces and (ES6) modules at the same time .使用 Node.js,您的文件是模块,那么您应该避免命名空间。

使用没有命名空间ES6 模块

TypeScript 很好地支持 ES6 模块的语法:

// UtilBase.ts
import * as path from "path";
export default class UtilBase {
    protected fixPath(value: string): string {
        return value.replace('/', path.sep);
    }
}

// UtilOne.ts
import UtilBase from './UtilBase';
export default class UtilOne extends UtilBase {
}

这是推荐的方式。 ES6 模块通过重命名每个导入资源的能力防止命名冲突。

它将在 Node.js 上运行。

有关 ES6 模块语法的详细介绍,read this article .

使用文件tsconfig.json而不是 /// <reference

注意:语法/// <referencethe file tsconfig.json 取代. Node.js 的示例:

// tsconfig.json
{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es6"
  },
  "exclude": [
    "node_modules"
  ]
}

关于typescript - 如何在 TypeScript 中通过导入使用命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37565709/

相关文章:

typescript - TypeScript错误TS2403 : Subsequent variable declarations must have the same type

TypeScript Visual Studio 语言扩展源代码

c++ - : "using namespace"?的目的是什么

c# - 命名空间 '<global namespace>' 包含与别名 'PersianDate' 冲突的定义

javascript - 没有babel的nodejs mocha es6模块意外 token 导出

javascript - 单元测试 ECMAScript 模块 (ESM) 和模拟本地状态?

javascript - `import * as Thing from ' .. .'` 是什么类型?

javascript promise 处理,无法处理错误

javascript - 尝试编写一个函数来确定复杂对象的深层嵌套子数组是否有值

.net-4.0 - .NET Framework 4.0 Beta2 中的 IObservable<T>