第一课, 体验typescriptjavascript
第三课, 什么是泛型?java
第四课, 解读高级类型git
第五课, 什么是命名空间(namespace)?github
若是你发现本身写的功能(函数/类/接口等...)愈来愈多, 你想对他们进行分组管理就能够用命名空间, 下面先用"类"举例:typescript
namespace Tools { const TIMEOUT = 100; export class Ftp { constructor() { setTimeout(() => { console.log('Ftp'); }, TIMEOUT) } } export class Http { constructor() { console.log('Http'); } } export function parseURL(){ console.log('parseURL'); } }
仔细看你会发现namespace
下还有export
, export
在这里用来表示哪些功能是能够外部访问的:segmentfault
Tools.TIMEOUT // 报错, Tools上没有这个属性 Tools.parseURL() // 'parseURL'
最后咱们看下编译成js后的代码:函数
"use strict"; var Tools; (function (Tools) { const TIMEOUT = 100; class Ftp { constructor() { setTimeout(() => { console.log('Ftp'); }, TIMEOUT); } } Tools.Ftp = Ftp; class Http { constructor() { console.log('Http'); } } Tools.Http = Http; function parseURL() { console.log('parseURL'); } Tools.parseURL = parseURL; })(Tools || (Tools = {}));
看js代码能发现, 在js中命名空间其实就是一个全局对象. 若是你开发的程序想要暴露一个全局变量就能够用namespace
;ui
命名空间不只能够用在逻辑代码中, 也能够用在类型, 用来给类型分组:this
namespace Food { export type A = Window; export interface Fruits{ taste: string; hardness: number; } export interface Meat{ taste: string; heat: number; } } let meat: Food.Meat; let fruits: Food.Fruits;
有2种方式, 一种/// <reference path="xxx.ts" />
, 还有就是import
:
经过reference
进行导入至关于xxx.ts
文件内的命名空间和当前文件进行了合并:
// xxx.ts namespace Food { export interface Fruits{ taste: string; hardness: number; } }
// yyy.ts <reference path="xxx.ts" /> let meat: Food.Meat; let fruits: Food.Fruits;
如今在yyy.ts
中咱们就能够直接使用xxx.ts
中的Food
类型了, 而不须要使用import
.
若是命名空间是用export
导出的, 那么使用的时候就不能够用/// <reference/>
了, 要用import
导入:
// xxx.ts // 使用export导出 export interface Fruits{ taste: string; hardness: number; } export interface Meat{ taste: string; heat: number; }
// yyy.ts import {Food} from './xxx'; // 使用import导入 let meat: Food.Meat; let fruits: Food.Fruits;
咱们知道接口是能够合并的, 命名空间也是能够的, 下面咱们把Vegetables
类型合并到Food
类型中:
// xxx.ts namespace Food { export interface Fruits{ taste: string; hardness: number; } }
// yyy.ts <reference path="xxx.ts" /> namespace Food { export interface Vegetables{ title: string; heat: number; } } type Vh = Food.Vegetables['heat'] // number;
若是你的tsconfig
中设置了"module": "umd",
, 那么export = Food
等价于export default Food
, export=
常见于支持umd的插件的声明文件.
其实咱们看下那些老牌插件(jq/lodash)里使用namespace
特性的代码, 能够发现主要是在声明文件中(xxx.d.ts), 用来表示暴露出来的全局变量(好比lodash的"_").
上面为了解释命名空间说起了声明文件(xxx.d.ts), 但因为声明(declare)的内容不少, 因此我会在下一节详细介绍.
其实若是你的项目直接是用ts写的可能用不上namespace
, 毕竟export
就能够产生模块, 模块自然就有隔离分组做用.
能力有限, 若是路过大神看到不对的地方还请多多指点, 我必虚心接受.
最后建议你们多写多练, 祝你们早日上手ts, 放几个我用ts写的项目当作参考, 抛砖引玉, 加油!
手势库, 支持点击/拖拽/旋转/缩放: https://github.com/any86/any-...
为vue组件生成this.$xxx的命令: https://github.com/any86/vue-...