前言

TypeScript 基础


安装 TypeScript

1
2
3
4
npm install -g typescript // 安装
tsc -V // 检查版本号

// 注:如果 ts 文件中只有 js 语法,html 引入改 ts 文件不会报错且可以执行

TypeScript中的基本类型

类型声明

1
2
3
4
5
6
// 语法
let 变量: 类型;
let 变量: 类型 = 值;
function fn(参数: 类型, 参数: 类型): 类型{
...
}

自动类型判断

  • TS拥有自动的类型判断机制
  • 当对变量的声明和赋值是同时进行的,TS编译器会自动判断变量的类型
  • 所以如果你的变量的声明和赋值时同时进行的,可以省略掉类型声明
1
2
3
// 如:let a = 1; 则 a 的类型为 number
let a = 1;
// a = 'hello world' 报错

类型

类型 例子 描述
number 1、-1、1.1 任意数字
string ‘hi’、”hi”、hi 任意字符串
boolean true、false 布尔值true或false
字面量 其本身 限制变量的值就是该字面量的值
any * 任意类型
unknown * 类型安全的any
void 空值(undefined) 没有值(或undefined)
never 没有值 不能是任何值
object { name: ‘孙悟空’ } 任意的JS对象
array [1,2,3] 任意JS数组
tuple [4,5] 元素,TS新增类型,固定长度数组
enum enum{A,B} 枚举,TS中新增类型
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/* number、string、boolean */
let num: number = 1;
let str: string = "hello world";
let bool: boolean = false;

/* 字面量 (配合 | 使用)*/
let sex: "男" | "女";
sex = "男";

/* any */
let val: any;
/* 等同于(默认就是 any)
let val */

/* unknown 类型安全的any */
let e: unknown;
e = 1;
e = true;
e = "字符串";

/* unknown 与 any 的区别 */
let z: any;
let x: unknown;
let c: string;
z = 1;
x = 1;
c = z; // any 可以赋值,影响了其他变量(不推荐 any )
/* 赋值 unknown 问题 */
// c = x 报错:不能将类型“unknown”分配给类型“string”
if (typeof x === "string") c = x;
// 类型断言( 告诉编辑器 x 就是字符串)
c = x as string;
c = <string>x;

/* void */
let unusable: void = undefined;
function fn(): void {}

/* never */
function error(message: string): never {
throw new Error(message);
}

/* object */
let obj: object;
obj = {};
obj = [];
obj = () => {};
// 用来指定对象中可以包含哪些属性
let o: { name: string };
o = { name: "xxx" };
// 必须要有 name 属性,其他任意属性( propName 写成其他都行 )
let ob: { name: string; [propName: string]: string };
ob = {name: 'xxx', x: 'xxx'}
// 限制函数格式
let fun: (a: number, b: number) => number;
// 剩余参数
function info(x: string, ...args: string[]) {
console.log(x, args)
}
// 可选参数
function fn(a: string, b?: string): string {
return a + b;
}

/* 函数重载: 函数名相同, 而形参不同的多个函数 */
// 重载函数声明
function add(x: string, y: string): string
function add(x: number, y: number): number
// 定义函数实现
function add(x: string | number, y: string | number): string | number | undefined {
// 在实现上我们要注意严格判断两个参数的类型是否相等,而不能简单的写一个 x + y
if (typeof x === 'string' && typeof y === 'string') {
return x + y
} else if (typeof x === 'number' && typeof y === 'number') {
return x + y
}
}
console.log(add(1, 2))
console.log(add('a', 'b'))
// console.log(add(1, 'a')) // error

/* Array */
let list: number[] = [1, 2, 3];
let arr: Array<number> = [1, 2, 3];

/* tuple 元组固定长度的数组 */
let arr1: [string, number];
arr1 = ["xxx", 2];

/* enum 枚举*/
enum Gender {
Male = "男", // 不写默认为 0
Female = "女", // 不写默认为 1
}

let i: { name: string; gender: Gender };
i = { name: "xxx", gender: Gender.Male };

/* & 的作用,表示且,都要满足 */
let n: { name: string } & { age: number };
n = { name: "xxx", age: 10 };

/* 类型的别名 (当什么比较长时,可以起别名)*/
type myType = 1 | 2 | 3 | 4 | 5;
let j: myType;
let k: myType;

编译选项

编译命令

1
2
3
4
5
6
7
8
tsc 文件.ts // 编译
// 如果编译报错 exports is not defined,因为编译后的产物为 commonjs 规范故报错
// 解决:修改 tsconfing.json 文件,"module": "commonjs" 注释
// 直接运行 tsc xxx.ts 会无效,因为该 tsc 命令没有与 tsconfing.json 关联
// 可以运行 tsc -w || tsc --project tsconfig.json 解决,其他更多参数参考官方文档
// 直接 tsc 就可以,不需要文件名,当然必须要有 tsconfig.json 文件

// 单独 ts 文件有重复声明的报错等,可以使用闭包(()=>{ })()、export default {} 解决

tsconfing.json 文件

include

  • 定义希望被编译文件所在的目录
  • 默认值:[“**/*”]

示例:

1
2
// ** 代表任意路径、 * 代表任意文件
"include":["src/**/*", "tests/**/*"]

上述示例中,所有src目录和tests目录下的文件都会被编译


exclude

  • 定义需要排除在外的目录
  • 默认值:[“node_modules”, “bower_components”, “jspm_packages”]

示例:

1
"exclude": ["./src/hello/**/*"]

上述示例中,src下hello目录下的文件都不会被编译


extends

  • 定义被继承的配置文件

示例:

1
"extends": "./configs/base"

上述示例中,当前配置文件中会自动包含config目录下base.json中的所有配置信息


files

  • 指定被编译文件的列表,只有需要编译的文件少时才会用到

示例:

1
2
3
4
5
6
7
8
9
10
11
12
"files": [
"core.ts",
"sys.ts",
"types.ts",
"scanner.ts",
"parser.ts",
"utilities.ts",
"binder.ts",
"checker.ts",
"tsc.ts"
]

  • 列表中的文件都会被TS编译器所编译

compilerOptions

  • 编译选项是配置文件中非常重要也比较复杂的配置选项
  • 在compilerOptions中包含多个子选项,用来完成对编译的配置

target

  • 设置ts代码编译的目标版本
  • 可选值:ES3(默认)、ES5、ES6/ES2015、ES7/ES2016、ES2017、ES2018、ES2019、ES2020、ESNext
1
2
3
"compilerOptions" : {
"target": "ES6"
}

lib

  • 指定代码运行时所包含的库(宿主环境)
  • 可选值:ES5、ES6/ES2015、ES7/ES2016、ES2017、ES2018、ES2019、ES2020、ESNext、DOM、WebWorker、ScriptHost ……
1
2
3
4
"compilerOptions" : {
// 如果是一个空数组的话,就表示什么库都不使用,没有相应提示(一般不需要动)
"lib": ["ES6", "DOM"],
}

module

  • 设置编译后代码使用的模块化系统
  • 可选值:CommonJS、UMD、AMD、System、ES2020、ESNext、None
1
2
3
"compilerOptions": {
"module": "CommonJS"
}

outDir

  • 编译后文件的所在目录
  • 默认情况下,编译后的js文件会和ts文件位于相同的目录,设置outDir后可以改变编译后文件的位置
1
2
3
"compilerOptions": {
"outDir": "dist"
}

outFile

  • 将所有的文件编译为一个js文件
  • 默认会将所有的编写在全局作用域中的代码合并为一个js文件,如果module制定了None、System或AMD则会将模块一起合并到文件之中
1
2
3
"compilerOptions": {
"outFile": "dist/app.js"
}

rootDir

  • 指定代码的根目录,默认情况下编译后文件的目录结构会以最长的公共目录为根目录,通过rootDir可以手动指定根目录
1
2
3
"compilerOptions": {
"rootDir": "./src"
}

allowJs

  • 是否对js文件编译

checkJs

  • 是否对js文件进行检查
1
2
3
4
"compilerOptions": {
"allowJs": true,
"checkJs": true
}

removeComments

  • 是否删除注释
  • 默认值:false

noEmit

  • 不对代码进行编译
  • 默认值:false

sourceMap

  • 是否生成sourceMap
  • 默认值:false

严格检查

  • strict:启用所有的严格检查,默认值为true,设置后相当于开启了所有的严格检查
  • alwaysStrict:总是以严格模式对代码进行编译
  • noImplicitAny:禁止隐式的any类型
  • noImplicitThis:禁止类型不明确的this
  • strictBindCallApply:严格检查bind、call和apply的参数列表
  • strictFunctionTypes:严格检查函数的类型
  • strictNullChecks:严格的空值检查
  • strictPropertyInitialization:严格检查属性是否初始化

额外检查

  • noFallthroughCasesInSwitch:检查switch语句包含正确的break
  • noImplicitReturns:检查函数没有隐式的返回值
  • noUnusedLocals:检查未使用的局部变量
  • noUnusedParameters:检查未使用的参数

高级

  • allowUnreachableCode:检查不可达代码,可选值:true 忽略不可达代码、false 不可达代码将引起错误
  • noEmitOnError:有错误的情况下不进行编译,默认值:false

面向对象

定义类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class 类名 {
属性名: 类型;
// 注:在TS中只能有一个构造器方法!
constructor(参数: 类型) {
this.属性名 = 参数;
}
方法名() {
....
}
// 静态属性,也称为类属性。使用静态属性无需创建实例,通过类即可直接使用
static 属性名: 类型 = 属性值
// 静态方法使用static开头
static 方法名() { ... }
}

// 示例
class Person {
name: string; // 此处申明属性
age: number = 18 // 这里也可以直接赋值(同样与 constructor 里面一样,只是无法使用变量)

constructor(name: string) {
this.name = name;
}

sayHello() {
console.log(`大家好,我是${this.name}`);
}

static PI = 3.1415926;
static sum(num1: number, num2: number){
return num1 + num2
}
}

// 使用
const p = new Person('孙悟空', 18);
p.sayHello();
console.log(Person.PI, Person.sum(123, 456));

类的继承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// 子类继承父类时,必须调用父类的构造方法(如果子类中也定义了构造方法则会重写该方法)
// 字如果有 constructor 则必须调用 super 否则会报错

class A {
num: number;
constructor(num: number) {
this.num = num;
}
fn() {
console.log(`父类中的fn方法!`, this.num);
}
}

class X extends A {
protected name: string;
constructor(num: number, name: string) {
super(num);
this.name = name;
}
fn() {
super.fn() // 调用父类的方法
console.log(`字类中的fn方法!`);
}
}

抽象类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 抽象类(abstract class)是专门用来被其他类所继承的类,它只能被其他类所继承不能用来创建实例
// 使用abstract开头的方法叫做抽象方法,
// 抽象方法没有方法体只能定义在抽象类中,继承抽象类时抽象方法必须要实现;
abstract class Animal{
abstract run(): void;
bark() {
console.log('动物在叫~');
}
}

class Dog extends Animals{
run() {
console.log('狗在跑~');
}
}

封装

对象实质上就是属性和方法的容器,它的主要作用就是存储属性和方法,这就是所谓的封装

默认情况下,对象的属性是可以任意的修改的,为了确保数据的安全性,在 TS 中可以对属性的权限进行设置

  • 静态属性(static)

    • 声明为 static 的属性或方法不再属于实例,而是属于类的属性;
  • 只读属性(readonly):

    • 如果在声明属性时添加一个 readonly,则属性便成了只读属性无法修改
  • TS中属性具有三种修饰符:

    • public(默认值)可以在类、子类和对象中修改
    • protected 可以在类、子类中修改
    • private 可以在类中修改

示例:

public:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// 使用 public 直接将属性定义在构造函数中
class C {
constructor(public name: string, public age: number) { }
}

class Person{
public name: string; // 写或什么都不写都是public
public age: number;

constructor(name: string, age: number){
this.name = name; // 可以在类中修改
this.age = age;
}

sayHello(){
console.log(`大家好,我是${this.name}`);
}
}

class Employee extends Person{
constructor(name: string, age: number){
super(name, age);
this.name = name; //子类中可以修改
}
}

const p = new Person('孙悟空', 18);
p.name = '猪八戒';// 可以通过对象修改

protected:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Person{
protected name: string;
protected age: number;

constructor(name: string, age: number){
this.name = name; // 可以修改
this.age = age;
}

sayHello(){
console.log(`大家好,我是${this.name}`);
}
}

class Employee extends Person{

constructor(name: string, age: number){
super(name, age);
this.name = name; //子类中可以修改
}
}

const p = new Person('孙悟空', 18);
p.name = '猪八戒';// 不能修改

private:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Person{
private name: string;
private age: number;

constructor(name: string, age: number){
this.name = name; // 可以修改
this.age = age;
}

sayHello(){
console.log(`大家好,我是${this.name}`);
}
}

class Employee extends Person{

constructor(name: string, age: number){
super(name, age);
this.name = name; //子类中不能修改
}
}

const p = new Person('孙悟空', 18);
p.name = '猪八戒';// 不能修改

属性存取器

对于一些不希望被任意修改的属性,可以将其设置为 private

直接将其设置为 private 将导致无法再通过对象修改其中的属性

我们可以在类中定义一组读取、设置属性的方法,这种对属性读取或设置的属性被称为属性的存取器

读取属性的方法叫做 setter 方法,设置属性的方法叫做 getter 方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Person{
private _name: string;

constructor(name: string){
this._name = name;
}

get name(){
return this._name;
}

set name(name: string){
this._name = name;
}

}

const p1 = new Person('孙悟空');
// 实际通过调用getter方法读取name属性
console.log(p1.name);
// 实际通过调用setter方法修改name属性
p1.name = '猪八戒';

接口

接口的作用类似于抽象类,不同点在于:接口中的所有方法和属性都是没有实值的,换句话说接口中的所有方法都是抽象方法;

接口主要负责定义一个类的结构,接口可以去限制一个对象的接口:对象只有包含接口中定义的所有属性和方法时才能匹配接口;

同时,可以让一个类去实现接口,实现接口时类中要保护接口中的所有属性;

注:接口可以重复申明,之后的会合并之前申明的;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
interface Person{
name: string;
sayHello():void;
}

class Student implements Person {
constructor(public name: string) {
this.name = name
}

sayHello() {
console.log('大家好,我是'+this.name);
}
}

接口补充

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// 属性修饰
interface IPerson {
readonly id: number // 只读属性
name: string // 默认必须
sex?: string // 可选属性
}

// 接口可以描述函数类型(参数的类型与返回的类型)
interface SearchFunc {
(source: string, subString: string): boolean
}
const mySearch: SearchFunc = function(source: string, sub: string): boolean {
return source.search(sub) > -1
}

// class 使用多个 interface
interface A {
fn1(): void
}
interface B {
fn2(): void
}

class C implements A, B {
fn1() {
console.log('fn1')
}
fn2() {
console.log('fn2')
}
}

// 接口继承接口
interface LightableAlarm extends Alarm, Light {}

泛型

泛型(Generic):定义一个函数或类时,有些情况下无法确定其中要使用的具体类型(返回值、参数、属性的类型不能确定);此时泛型便能够发挥作用;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
function test(arg: any): any{
return arg;
}
// 上例中,test函数有一个参数类型不确定,但是能确定的时其返回值的类型和参数的类型是相同的;
// 由于类型不确定所以参数和返回值均使用了any,但是很明显这样做是不合适的:
// 首先使用any会关闭TS的类型检查,其次这样设置也不能体现出参数和返回值是相同的类型;

function test<T>(arg: T): T{
return arg;
}
// T是我们给这个类型起的名字(不一定非叫T),设置泛型后即可在函数中使用T来表示该类型;
// 所以泛型其实很好理解,就表示某个类型;
// 那么如何使用上边的函数呢?
test(10) // 直接使用
test<number>(10) // 指定类型


// 可以同时指定多个泛型,泛型间使用逗号隔开
function test<T, K>(a: T, b: K): K{
return b;
}
test<number, string>(10, "hello");


// 类中同样可以使用泛型
class MyClass<T>{
prop: T;
constructor(prop: T){
this.prop = prop;
}
}


// 除此之外,也可以对泛型的范围进行约束
// 使用T extends MyInter表示泛型T必须是MyInter的子类,不一定非要使用接口类和抽象类同样适用
interface MyInter{
length: number;
}
function test<T extends MyInter>(arg: T): number{
return arg.length;
}

// 泛型接口
interface IbaseCRUD<T> {
data: T[]
add: (t: T) => void
getById: (id: number) => T
}

class User {
id?: number //id主键自增
name: string //姓名
age: number //年龄

constructor(name, age) {
this.name = name
this.age = age
}
}

class UserCRUD implements IbaseCRUD<User> {
data: User[] = []

add(user: User): void {
user = { ...user, id: Date.now() }
this.data.push(user)
console.log('保存user', user.id)
}

getById(id: number): User {
return this.data.find(item => item.id === id)
}
}

const userCRUD = new UserCRUD()
userCRUD.add(new User('tom', 12))
userCRUD.add(new User('tom2', 13))
console.log(userCRUD.data)

声明文件

1
2
3
4
5
6
7
8
9
10
11
/*
当使用第三方库时,我们需要引用它的声明文件,才能获得对应的代码补全、接口提示等功能。
声明语句: 如果需要ts对新的语法进行检查, 需要要加载了对应的类型说明代码
declare var jQuery: (selector: string) => any;
声明文件: 把声明语句放到一个单独的文件(jQuery.d.ts)中, ts会自动解析到项目中所有声明文件
*/

// declare var 并没有真的定义一个变量,只是定义了全局变量 jQuery 的类型,
// 仅仅会用于编译时的检查,在编译结果中会被删除。
declare var jQuery: (selector: string) => any
jQuery('#foo')

内置对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/* 1. ECMAScript 的内置对象 */
let b: Boolean = new Boolean(1)
let n: Number = new Number(true)
let s: String = new String('abc')
let d: Date = new Date()
let r: RegExp = /^1/
let e: Error = new Error('error message')
b = true
// let bb: boolean = new Boolean(2) // error


const div: HTMLElement = document.getElementById('test')
const divs: NodeList = document.querySelectorAll('div')
document.addEventListener('click', (event: MouseEvent) => {
console.dir(event.target)
})
const fragment: DocumentFragment = document.createDocumentFragment()

Vue3 对 TS 支持

参考:TypeScript 与组合式 API

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/** defineProps 与 ts */
interface Props {
name?: string,
title: number,
status?: boolean
}
const props = defineProps<Props>()
// 注意:不支持
import { Props } from './Props'
defineProps<Props>()
// 设置默认值
const props = withDefaults(defineProps<{
name: string
title?: string
num: number[]
}>(), {
title: '测试标题',
num: () => [10, 20, 30, 40, 50]
})

/** emits 标注类型 */
const emit = defineEmits<{
(e: 'change', id: number): void
(e: 'update', value: string): void
}>()

/** ref */
const year = ref<string | number>('2020')

/** reactive */
interface Book {
title: string
year?: number
}
const book: Book = reactive({ title: 'Vue 3 指引' })
// 不推荐使用 reactive() 的泛型参数,因为处理了深层次 ref 解包的返回值与泛型参数的类型不同。

/** computed */
const double = computed<number>(() => {
// 若返回值不是 number 类型则会报错
})

/** 事件处理函数 */
function handleChange(event: Event) {
console.log((event.target as HTMLInputElement).value)
}

TypeScript 补充

  • 严格模式下 null 不能赋予 void 类型,非严格模式下 undefined 和 null 是所有类型的子类型

  • any 与 unknown 区别

1
2
3
4
5
// unknown 是不能调用属性和方法;而 any 类型可以
let obj: unknown = { a: 1, b: (): number => 2 };
// 会报错 “obj”的类型为“未知”。
obj.b;
obj.ccc();
  • object 、Object 、{} 区别
1
2
3
4
5
6
7
8
9
/*
1.Object 是该类型是所有 Object 类的实例的类型,原型链的顶端是 Object
2.object 是所有的引用类型,原始类型不支持
3.{} 是与 Object 一样
*/
// 注意:直接使用Object、object、{} 是无法直接访问属性
let a: object = {b: 1}
console.log(a.b) // 类型“object”上不存在属性“b”。
// 解决:使用 自动类型推导 、指定对象中可以包含哪些属性、 接口interface
  • interface
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/*
1. 重名时会合并,interface 和 type 中可以用分号或逗号、class 中只能用分号
2. 随意key
interface Person {
[propName: string]: any; // 这里要写成 any,不然下面的会报错
b?:string,
a:string,
}
3. 接口定义函数
interface Fn {
(name: string): number[]
}
const fn = ()
*/
  • 数组类型
1
2
3
4
5
6
7
// 1. 定义二维数组
let arr: number[][] = [[1], [2]]
let arr: []<Array><number> = [[1], [2]]
// 2. 定义 arguments
function () {
let a:IArguments = arguments
}
  • 函数类型
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 1. 函数定义 this (必须是函数的第一个参数)
interface Obj {
name: string;
fn: (this: Obj) => string;
}

let obj: Obj = {
name: "foo",
fn(this: Obj): string {
return this.name;
},
};

console.log(obj.fn())
  • 类型断言
1
(window as any).a = 1
  • 内置对象
1
2
3
4
5
6
7
8
let el1: HTMLDivElement | null = document.querySelector("div");
let el2: NodeList = document.querySelectorAll("div");
let el3: NodeListOf<HTMLDivElement> = document.querySelectorAll("div");
let el4: NodeListOf<HTMLDivElement | Element> = document.querySelectorAll("div");
let loc: Storage = localStorage;
let lo: Location = location;
let co:string = document.cookie
let P: Promise<number> = new Promise((v) => v(1)); // 泛型申明返回值
  • class
1
// 1. static 里面的 this 只能调用加了 static 的方法与属性
  • 元组
1
2
3
4
5
6
7
8
// 元组的长度是固定的,但可以调用 push 等方法改变度。
// 直接使用索引值修改元组中的元素是不允许的。
let arr: [number, number, string] = [1, 2, '3'];
arr.push('5')
console.log(arr)
// 使用 readonly 修饰符,可以不让更改
let arr1: readonly [number, string] = [1, '2'];
let arr1: readonly [x: number, y?: string] = [1, "2"];
  • 枚举类型
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// const枚举,let 和 var 都是不允许的声明只能使用 const
// const 声明的枚举会被编译成常量,避免在额外生成的代码上的开销和额外的非直接的对枚举成员的访问
const enum Types {
No = "No",
Yes = 1,
}

// 反向映射
// 它包含了正向映射( name -> value)和反向映射( value -> name)
// 要注意的是 不会为字符串枚举成员生成反向映射。
enum Enum {
fall
}
let a = Enum.fall;
console.log(a); //0
let nameOfA = Enum[a];
console.log(nameOfA); // fall
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
namespace a {
export const a1 = 1;
export namespace b {
export const a2 = 2;
}
}
console.log(a.a1);
console.log(a.b.a2);

// 别名
import B = a.b;
console.log(B.a2);

/* 抽离命名空间
export namespace V {
export const a = 1
}
import { V } from '../observer/index'
*/

// 命名空间有多个时会合并(类似于 interface )
  • 三斜线指令:在编译过程中要引入的额外的文件、三斜线指令仅可最顶端
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/* index1.ts */
namespace A {
export const a = 'a'
}

/* index2.ts */
///<reference path="./index1.ts" />
namespace A {
export const b = 'b'
}

console.log(A);

// 注意:outFile 需要开启,并且 module 为 AMD

// 声明文件导入,使用了 @types/node/index.d.ts 里面声明的名字( node_modules 下)
///<reference types="node" />
  • 声明文件(没有声明文件就会报错)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
declare var 声明全局变量
declare function 声明全局方法
declare class 声明全局类
declare enum 声明全局枚举类型
declare namespace 声明(含有子属性的)全局对象
interface 和 type 声明全局类型
/// <reference /> 三斜线指令

// 声明文件手写参考 express.d.ts ( 最好统一放在 typings文件夹下 )
declare module 'express' {
interface Router {
get(path: string, cb: (req: any, res: any) => void): void
}
interface App {

use(path: string, router: any): void
listen(port: number, cb?: () => void): void
}
interface Express {
(): App
Router(): Router

}
const express: Express
export default express
}