六、模块及命名空间

官网文档地址 https://www.typescriptlang.org/docs/handbook/generics.html

模块

我们可以把一些公共的功能单独抽离成一个文件作为一个模块。模块里面的变量/函数/类等默认时私有的,如果我们要在外部访问模块里面的数据(变量/函数/类)我们需要通过export暴露模块里面的数据(变量/函数/类)。暴露后我们通过import引入模块就可以使用模块里面暴露的数据(变量/函数/类)等。

关键字
export
import from
export default
用法
export 导出
import 导入  from 模块文件
------------------
export class SomeType { /* ... */ }
export function someFunc() { /* ... */ }
export * from "./StringValidator";
export default class ZipCodeValidator {}//default 只能有一个。
export {aa, bb ,cc } // 一次暴露多个变量或函数或类
=====
import { SomeType as aa, someFunc } from "./MyThings";// as 可起别名
import validator from "./ZipCodeValidator"; // 当为export default暴露时可不使用{},default 只能有一个。
let x = new SomeType();
let y = someFunc();
------------------

export = 对应 import = require()
CommonJS和AMD通常都有一个导出对象的概念,它包含了一个模块的所有导出。TypeScript supports export = to model the traditional CommonJS and AMD workflow.
------------------
class ZipCodeValidator {}
export = ZipCodeValidator;
=====
import zip = require("./ZipCodeValidator");
// Some samples to try
let strings = ["Hello", "98052", "101"];
-----------------
命名空间

内部模块,主要用于组织代码,避免命名冲突。

模块为ts的外部模块的简称,侧重代码的复用,一个模块里可能会有多个。

export namespace Validation {
    const lettersRegexp = /^[A-Za-z]+$/;
    export class LettersOnlyValidator implements StringValidator {
        isAcceptable(s: string) {
            return lettersRegexp.test(s);
        }
    }
}


/// <reference path="Validation.ts" /> // '///'方式引入命名空间,该方式可能新版本会不支持
import {Validation} from './ss'
let a = new Validation.LettersOnlyValidator('d');
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值