模块系统
-
1.ES6模块
-
1.1分开导入导出
- export xxx;
- import {xxx} from "path";
-
1.2一次性导入导出
- export {xxx, yyy, zzz};
- import {xxx, yyy, zzz} from "path";
-
1.3默认导入导出
- export default xxx;
- import xxx from "path";
-
2.Node模块
-
2.1通过exports.xxx = xxx导出
- 通过const xxx = require("path");导入
- 通过const {xx, xx} = require("path");导入
-
2.2通过module.exports.xxx = xxx导出
- 通过const xxx = require("path");导入
- 通过const {xx, xx} = require("path");导入
- ES6的模块和Node的模块是不兼容的, 所以TS为了兼容两者就推出了
- export = xxx;
- import xxx = require('path');
命名空间
- 命名空间可以看做是一个微型模块,
- 当我们先把相关的业务代码写在一起, 又不想污染全局空间的时候
namespace Validation {
const lettersRegexp = /^[A-Za-z]+$/
export const LettersValidator = (value) => {
return lettersRegexp.test(value)
}
}
// 可以通过 reference 来引入其他文件的命名空间
// /// <reference path="./56/test.ts" />
console.log(Validation.LettersValidator('abc'))
console.log(Validation.LettersValidator(123))
命名空间合并
- 在 ts当中接口和命名空间 是可以重名的
- ts会将多个同名的合并为一个
interface TestInterface {
name: string
}
interface TestInterface {
age: number
}
class Person implements TestInterface {
name: string
age: number
}
// 注意点: 如果同名接口中的属性名相同, 那么属性类型必须一致
// subsequent property declarations must have the same type. Property 'name' must be of type 'string', but here has type 'boolean'.
// interface TestInterface {
// name: boolean
// }
- 同名接口如果出现同名函数, 那么就会成一个函数的重载
interface TestInterface1 {
getValue(value: number): number
}
interface TestInterface1 {
getValue(value: string): number
}
let obj: TestInterface1 = {
getValue(value: any): number {
if (typeof value === 'string') {
return value.length
} else {
return value.toFixed()
}
},
}
- 命名空间合并
namespace Test {
export let name: string = 'css'
}
namespace Test {
export let age: number = 12
}
console.log(Test.name)
console.log(Test.age)
- 同名的命名空间中不能出现同名的变量, 方法等
namespace Test1 {
export let name: string = 'js'
export let age: number = 112
}
// 报错
// namespace Test1 {
// export let name: string = 'js'
// export let age: number = 112
// }
- 同名的命名空间中其他命名空间没有通过 export到处的内容是获取不到
namespace Test2 {
let name: string = 'java'
}
namespace Test2 {
export let say = () => {
console.log(`name is ${name}`)
}
}
Test2.say() // name is
- 除了同名的接口和命名空间可以合并以外
- 命名空间还可以和同名的类 / 函数/ 枚举合并
命名空间和类合并
- 注意点: 类必须定义在命名空间的前面
- 会将命名空间中导出的方法作为一个静态方法合并到类中
class Person1 {
say(): void {
console.log('32', 32)
}
}
namespace Person1 {
export let eat = () => {
console.log('1', 1)
}
}
console.dir(Person1)
// eat 作为一个静态方法合并到类中
Person1.eat()
let p = new Person1()
p.say()
命名空间和函数合并
- 注意点:函数必须定义在命名空间的前面
function getCounter() {
getCounter.count++
console.log(getCounter.count)
}
namespace getCounter {
export let count: number = 1
}
getCounter() // 2
命名空间和枚举合并
- 注意点:没有先后顺序的要求
enum Gender {
Male,
Female,
}
namespace Gender {
export const Yao: number = 66
}
console.log(Gender)













网友评论