@@ -66,7 +66,7 @@ function isFish(animal: Cat | Fish) {
66
66
// Property 'swim' does not exist on type 'Cat'.
67
67
```
68
68
69
- 上例中 ,获取 ` animal.swim ` 的时候会报错。
69
+ 上面的例子中 ,获取 ` animal.swim ` 的时候会报错。
70
70
71
71
此时可以使用类型断言,将 ` animal ` 断言成 ` Fish ` :
72
72
@@ -90,7 +90,7 @@ function isFish(animal: Cat | Fish) {
90
90
91
91
这样就可以解决访问 ` animal.swim ` 时报错的问题了。
92
92
93
- 需要注意的是,类型断言只能够「欺骗」TypeScript 编译器,无法避免运行时的错误,甚至与滥用类型断言可能会导致运行时错误 :
93
+ 需要注意的是,类型断言只能够「欺骗」TypeScript 编译器,无法避免运行时的错误,甚至于滥用类型断言可能会导致运行时错误 :
94
94
95
95
``` ts
96
96
interface Cat {
@@ -106,11 +106,11 @@ function swim(animal: Cat | Fish) {
106
106
(animal as Fish ).swim ();
107
107
}
108
108
109
- const cat : Cat = {
109
+ const tom : Cat = {
110
110
name: ' Tom' ,
111
- run() { console .log (' run' ); }
111
+ run() { console .log (' run' ) }
112
112
};
113
- swim (cat );
113
+ swim (tom );
114
114
```
115
115
116
116
上面的例子编译时不会报错,但在运行时会报错:
@@ -220,7 +220,7 @@ foo.length = 1;
220
220
// index.ts:2:5 - error TS2339: Property 'length' does not exist on type 'number'.
221
221
```
222
222
223
- 上例中 ,数字类型的变量 ` foo ` 上是没有 ` length ` 属性的,故 TypeScript 给出了相应的错误提示。
223
+ 上面的例子中 ,数字类型的变量 ` foo ` 上是没有 ` length ` 属性的,故 TypeScript 给出了相应的错误提示。
224
224
225
225
这种错误提示显然是非常有用的。
226
226
@@ -232,7 +232,7 @@ window.foo = 1;
232
232
// index.ts:1:8 - error TS2339: Property 'foo' does not exist on type 'Window & typeof globalThis'.
233
233
```
234
234
235
- 上例中 ,我们需要将 ` window ` 上添加一个属性 ` foo ` ,但 TypeScript 编译时会报错,提示我们 ` window ` 上不存在 ` foo ` 属性。
235
+ 上面的例子中 ,我们需要将 ` window ` 上添加一个属性 ` foo ` ,但 TypeScript 编译时会报错,提示我们 ` window ` 上不存在 ` foo ` 属性。
236
236
237
237
此时我们可以使用 ` as any ` 临时将 ` window ` 断言为 ` any ` 类型:
238
238
@@ -312,11 +312,11 @@ interface Cat {
312
312
run(): void ;
313
313
}
314
314
315
- let cat : Cat = {
315
+ let tom : Cat = {
316
316
name: ' Tom' ,
317
317
run : () => { console .log (' run' ) }
318
318
};
319
- let animal: Animal = cat ;
319
+ let animal: Animal = tom ;
320
320
```
321
321
322
322
我们知道,TypeScript 是结构类型系统,类型之间的对比只会比较它们最终的结构,而会忽略它们定义时的关系。
@@ -332,7 +332,7 @@ interface Cat extends Animal {
332
332
}
333
333
```
334
334
335
- 那么也不难理解为什么 ` Cat ` 类型的 ` cat ` 可以赋值给 ` Animal ` 类型的 ` animal ` 了——就像面向对象编程中我们可以将子类的实例赋值给类型为父类的变量。
335
+ 那么也不难理解为什么 ` Cat ` 类型的 ` tom ` 可以赋值给 ` Animal ` 类型的 ` animal ` 了——就像面向对象编程中我们可以将子类的实例赋值给类型为父类的变量。
336
336
337
337
我们把它换成 TypeScript 中更专业的说法,即:` Animal ` 兼容 ` Cat ` 。
338
338
@@ -378,7 +378,7 @@ function testCat(cat: Cat) {
378
378
- any 可以被断言为任何类型
379
379
- 要使得 ` A ` 能够被断言为 ` B ` ,只需要 ` A ` 兼容 ` B ` 或 ` B ` 兼容 ` A ` 即可
380
380
381
- 其实前两种情况都是最后一个的特例 。
381
+ 其实前四种情况都是最后一个的特例 。
382
382
383
383
## 双重断言
384
384
@@ -556,7 +556,7 @@ const tom: Cat = getCacheData('tom');
556
556
557
557
> 本小结的前置知识点:[ 范型] [ ]
558
558
559
- 在这个例子中 :
559
+ 还是这个例子 :
560
560
561
561
``` ts
562
562
function getCacheData(key : string ): any {
0 commit comments