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

Skip to content

Commit c4f4bab

Browse files
authored
添加一个用法举例
1 parent 692327d commit c4f4bab

File tree

1 file changed

+12
-0
lines changed

1 file changed

+12
-0
lines changed

basics/type-assertion.md

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,18 @@ function getLength(something: string | number): number {
6060
}
6161
```
6262

63+
64+
65+
```ts
66+
function getLength(something: string | number): number {
67+
if ((something as string).length) {
68+
return (something as string).length;
69+
} else {
70+
return something.toString().length;
71+
}
72+
}
73+
```
74+
6375
类型断言的用法如上,在需要断言的变量前加上 `<Type>` 即可。
6476

6577
**类型断言不是类型转换,断言成一个联合类型中不存在的类型是不允许的**

0 commit comments

Comments
 (0)