Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 97df13b

Browse files
committed
Add Generics
1 parent 6d66461 commit 97df13b

16 files changed

+198
-26
lines changed

.vscode/launch.json

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
{
2+
// Use IntelliSense to learn about possible Node.js debug attributes.
3+
// Hover to view descriptions of existing attributes.
4+
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
5+
"version": "0.2.0",
6+
"configurations": [
7+
{
8+
"type": "node",
9+
"request": "launch",
10+
"name": "启动程序",
11+
"program": "${workspaceRoot}/app.ts",
12+
"cwd": "${workspaceRoot}",
13+
"outFiles": [],
14+
"sourceMaps": true
15+
},
16+
{
17+
"type": "node",
18+
"request": "attach",
19+
"name": "附加到进程",
20+
"port": 5858,
21+
"outFiles": [],
22+
"sourceMaps": true
23+
}
24+
]
25+
}

SUMMARY.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,18 +7,18 @@
77
- [Hello TypeScript](introduction/hello-typescript.md)
88
- [基础](basics/README.md)
99
- [原始数据类型](basics/primitive-data-types.md)
10-
- [任意值(Any)](basics/any.md)
10+
- [任意值](basics/any.md)
1111
- [类型推论](basics/type-inference.md)
1212
- [联合类型](basics/union-types.md)
1313
- [对象的类型——接口](basics/type-of-object-interfaces.md)
1414
- [数组的类型](basics/type-of-array.md)
1515
- [函数的类型](basics/type-of-function.md)
16-
- [声明文件(.d.ts)](basics/declaration-files.md)
16+
- [声明文件](basics/declaration-files.md)
1717
- [内置对象](basics/built-in-objects.md)
1818
- 进阶(未完成)
1919
- [类的用法](advanced/use-of-class.md)
2020
- [类的类型](advanced/type-of-class.md)
21-
- [元组(Tuple)](advanced/tuple.md)
22-
- [枚举(Enum)](advanced/enum.md)
21+
- [元组](advanced/tuple.md)
22+
- [枚举](advanced/enum.md)
2323
- 实践(未完成)
2424
- 学习资料(未完成)

advanced/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
## 进阶
2+
3+
---

advanced/enum.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 枚举(Enum)
1+
# 枚举
22

33
枚举(Enum)类型用于取值被限定在一定范围内的场景,比如一周只能有七天,颜色限定为红绿蓝等。
44

@@ -222,3 +222,5 @@ var directions = [0 /* Up */, 1 /* Down */, 2 /* Left */, 3 /* Right */];
222222

223223
[中文手册 - 枚举]: https://zhongsp.gitbooks.io/typescript-handbook/content/doc/handbook/Enums.html
224224
[C# Enum]: https://msdn.microsoft.com/zh-cn/library/sbbt4032.aspx
225+
226+
---

advanced/generics.md

Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
1+
# 泛型
2+
3+
泛型(Generics)是指在定义函数、接口或类的时候,不预先指定具体的类型,而在使用的时候再指定类型的一种特性。
4+
5+
## 简单的例子
6+
7+
首先,我们来实现一个函数 `createArray`,它可以创建一个指定长度的数组,同时将每一项都填充一个默认值:
8+
9+
```ts
10+
function createArray(length: number, value: any): Array<any> {
11+
let result = [];
12+
for (let i = 0; i < length; i++) {
13+
result[i] = value;
14+
}
15+
return result;
16+
}
17+
18+
createArray(3, 'x'); // ['x', 'x', 'x']
19+
```
20+
21+
上例中,我们使用了[之前提到过的数组泛型](../basics/type-of-array.md#数组泛型)来定义返回值的类型。
22+
23+
这段代码编译不会报错,但是一个显而易见的缺陷是,它并没有准确的定义返回值的类型:
24+
25+
`Array<any>` 允许数组的每一项都为任意类型。但是我们预期的是,数组中每一项都应该是输入的 `value` 的类型。
26+
27+
这时候,泛型就派上用场了:
28+
29+
```ts
30+
function createArray<T>(length: number, value: T): Array<T> {
31+
let result = [];
32+
for (let i = 0; i < length; i++) {
33+
result[i] = value;
34+
}
35+
return result;
36+
}
37+
38+
createArray<string>(3, 'x'); // ['x', 'x', 'x']
39+
```
40+
41+
上例中,我们在函数名后添加了 `<T>`,其中 `T` 用来指代任意输入的类型,在后面的输入 `value: T` 和输出 `Array<T>` 中即可使用了。
42+
43+
接着在调用的时候,可以指定它具体的类型为 `string`。当然,也可以不手动指定,而让类型推论自动推算出来:
44+
45+
```ts
46+
function createArray<T>(length: number, value: T): Array<T> {
47+
let result = [];
48+
for (let i = 0; i < length; i++) {
49+
result[i] = value;
50+
}
51+
return result;
52+
}
53+
54+
createArray(3, 'x'); // ['x', 'x', 'x']
55+
```
56+
57+
## 多个类型参数
58+
59+
定义泛型的时候,可以一次定义多个类型参数:
60+
61+
```ts
62+
function swap<T, U>(tuple: [T, U]): [U, T] {
63+
return [tuple[1], tuple[0]];
64+
}
65+
66+
swap([7, 'seven']); // ['seven', 7]
67+
```
68+
69+
上例中,我们定义了一个 `swap` 函数,用来交换输入的元组。
70+
71+
## 泛型约束
72+
73+
在函数内部使用泛型变量的时候,由于事先不知道它是哪种类型,所以不能随意的操作它的属性或方法:
74+
75+
```ts
76+
function loggingIdentity<T>(arg: T): T {
77+
console.log(arg.length);
78+
return arg;
79+
}
80+
81+
// index.ts(2,19): error TS2339: Property 'length' does not exist on type 'T'.
82+
```
83+
84+
上例中,泛型 `T` 不一定包含属性 `length`,所以编译的时候报错了。
85+
86+
这时,我们可以对泛型进行约束,只允许这个函数传入那些包含 `length` 属性的变量。这就是泛型约束:
87+
88+
```ts
89+
interface Lengthwise {
90+
length: number;
91+
}
92+
93+
function loggingIdentity<T extends Lengthwise>(arg: T): T {
94+
console.log(arg.length);
95+
return arg;
96+
}
97+
```
98+
99+
上例中,我们使用了 `extends` 约束了泛型 `T` 必须符合接口 `Lengthwise` 的形状,也就是必须包含 `length` 属性。
100+
101+
此时如果调用 `loggingIdentity` 的时候,传入的 `arg` 不包含 `length`,那么在编译阶段就会报错了:
102+
103+
```ts
104+
interface Lengthwise {
105+
length: number;
106+
}
107+
108+
function loggingIdentity<T extends Lengthwise>(arg: T): T {
109+
console.log(arg.length);
110+
return arg;
111+
}
112+
113+
loggingIdentity(7);
114+
115+
// index.ts(10,17): error TS2345: Argument of type '7' is not assignable to parameter of type 'Lengthwise'.
116+
```
117+
118+
多个类型参数之间也可以互相约束:
119+
120+
```ts
121+
TBD
122+
```
123+
124+
## 泛型接口
125+
126+
TBD
127+
128+
## 泛型类
129+
130+
TBD
131+
132+
## 参考
133+
134+
- [Handbook - Generics](http://www.typescriptlang.org/docs/handbook/generics.html) | [中文版](https://zhongsp.gitbooks.io/typescript-handbook/content/doc/handbook/generics.html)
135+
136+
---

advanced/tuple.md

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
# 元组(Tuple)
1+
# 元组
22

3-
元组表示一些特定类型组合成的**数组**类型。
3+
元组(Tuple)表示一些特定类型组合成的**数组**类型。
44

55
## 简单的例子
66

@@ -92,4 +92,6 @@ console.log(xcatliu[2].slice(1));
9292
- [Handbook - Basic Types # Tuple](http://www.typescriptlang.org/docs/handbook/basic-types.html#tuple) | [中文版](https://zhongsp.gitbooks.io/typescript-handbook/content/doc/handbook/Basic%20Types.html#元组-tuple)
9393
- [C# Tuple]
9494

95+
---
96+
9597
[C# Tuple]: https://msdn.microsoft.com/en-us/library/system.tuple(v=vs.110).aspx

basics/README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,13 @@
33
本部分介绍了 TypeScript 中的常用类型和一些基本概念,旨在让大家对 TypeScript 有个初步的理解。具体内容包括:
44

55
- [原始数据类型](primitive-data-types.md)
6-
- [任意值(Any)](any.md)
6+
- [任意值](any.md)
77
- [类型推论](type-inference.md)
88
- [联合类型](union-types.md)
99
- [对象的类型——接口](type-of-object-interfaces.md)
1010
- [数组的类型](type-of-array.md)
1111
- [函数的类型](type-of-function.md)
12-
- [声明文件(.d.ts)](declaration-files.md)
12+
- [声明文件](declaration-files.md)
1313
- [内置对象](built-in-objects.md)
1414

1515
---

basics/any.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 任意值(Any)
1+
# 任意值
22

33
任意值(Any)用来表示允许赋值为任意类型。
44

basics/built-in-objects.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,5 +108,5 @@ npm install @types/node --save-dev
108108

109109
---
110110

111-
- [上一章:声明文件(.d.ts)](declaration-files.md)
111+
- [上一章:声明文件](declaration-files.md)
112112
- [下一章:进阶](../advanced/README.md)

basics/declaration-files.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 声明文件(.d.ts)
1+
# 声明文件
22

33
当使用第三方库时,我们需要引用它的声明文件。
44

basics/primitive-data-types.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,7 @@ let num: number = u;
154154
---
155155

156156
- [上一章:基础](README.md)
157-
- [下一章:任意值(Any)](any.md)
157+
- [下一章:任意值](any.md)
158158

159159
[Primitive data types]: https://developer.mozilla.org/en-US/docs/Glossary/Primitive
160160
[ES6 中的新类型 `Symbol`]: http://es6.ruanyifeng.com/#docs/symbol

basics/type-inference.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,5 +38,5 @@ myFavoriteNumber = 7;
3838

3939
---
4040

41-
- [上一章:任意值(Any)](any.md)
41+
- [上一章:任意值](any.md)
4242
- [下一章:联合类型](union-types.md)

basics/type-of-array.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,15 +29,15 @@ fibonacci.push('8');
2929
// index.ts(2,16): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
3030
```
3131

32-
## 数组泛型(Generic)
32+
## 数组泛型
3333

34-
也可以使用数组泛型 `Array<elemType>` 来表示数组:
34+
也可以使用数组泛型(Generic) `Array<elemType>` 来表示数组:
3535

3636
```ts
3737
let fibonacci: Array<number> = [1, 1, 2, 3, 5];
3838
```
3939

40-
关于泛型,可以参考???一章。
40+
关于泛型,可以参考[《泛型》](../advanced/generics.md)一章。
4141

4242
## 用接口表示数组
4343

basics/type-of-function.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -187,4 +187,4 @@ push(a, 1, 2, 3);
187187
---
188188

189189
- [上一章:数组的类型](type-of-array.md)
190-
- [下一章:声明文件(.d.ts)](declaration-files.md)
190+
- [下一章:声明文件](declaration-files.md)

examples/playground/index.js

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
function sayHello(person) {
2-
return 'Hello, ' + person;
1+
function loggingIdentity(arg) {
2+
console.log(arg.length);
3+
return arg;
34
}
4-
var user = [0, 1, 2];
5-
document.body.innerHTML = sayHello(user);
5+
loggingIdentity(7);

examples/playground/index.ts

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
1-
function sayHello(person: string) {
2-
return 'Hello, ' + person;
1+
interface Lengthwise {
2+
length: number;
33
}
44

5-
let user = [0, 1, 2];
6-
document.body.innerHTML = sayHello(user);
5+
function loggingIdentity<T extends Lengthwise>(arg: T): T {
6+
console.log(arg.length);
7+
return arg;
8+
}
9+
10+
loggingIdentity(7);

0 commit comments

Comments
 (0)