You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
function getLength(something:string|number):number {
11
+
returnsomething.length;
12
+
}
13
+
14
+
// index.ts(2,20): error TS2339: Property 'length' does not exist on type 'string | number'.
15
+
// Property 'length' does not exist on type 'number'.
16
+
```
17
+
18
+
而有时候,我们确实需要在还不确定类型的时候就访问其中一个类型的属性或方法,比如:
19
+
20
+
```ts
21
+
function getLength(something:string|number):number {
22
+
if (something.length) {
23
+
returnsomething.length;
24
+
} else {
25
+
returnsomething.toString().length;
26
+
}
27
+
}
28
+
29
+
// index.ts(2,17): error TS2339: Property 'length' does not exist on type 'string | number'.
30
+
// Property 'length' does not exist on type 'number'.
31
+
// index.ts(3,22): error TS2339: Property 'length' does not exist on type 'string | number'.
32
+
// Property 'length' does not exist on type 'number'.
33
+
```
34
+
35
+
上例中,获取 `something.length` 的时候会报错。
36
+
37
+
此时可以使用类型断言,将 `something` 断言成 `string`:
38
+
39
+
```ts
40
+
function getLength(something:string|number):number {
41
+
if ((<string>something).length) {
42
+
return (<string>something).length;
43
+
} else {
44
+
returnsomething.toString().length;
45
+
}
46
+
}
47
+
```
48
+
49
+
类型断言的用法如上,在需要断言的变量前加上 `<Type>` 即可。
50
+
51
+
**类型断言不是类型转换,断言成一个联合类型中不存在的类型是不允许的**:
52
+
53
+
```ts
54
+
function toBoolean(something:string|number):boolean {
55
+
return <boolean>something;
56
+
}
57
+
58
+
// index.ts(2,10): error TS2352: Type 'string | number' cannot be converted to type 'boolean'.
59
+
// Type 'number' is not comparable to type 'boolean'.
60
+
```
61
+
62
+
## 参考
63
+
64
+
-[Advanced Types # Type Guards and Differentiating Types](http://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-differentiating-types) | [中文版](https://zhongsp.gitbooks.io/typescript-handbook/content/doc/handbook/Advanced%20Types.html#类型保护与区分类型(type-guards-and-differentiating-types))
0 commit comments