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

Skip to content

Commit 954cc72

Browse files
authored
Merge pull request xcatliu#92 from LDWX/master
add instructions for propName
2 parents 21849cb + c4f4bab commit 954cc72

File tree

3 files changed

+31
-2
lines changed

3 files changed

+31
-2
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
**类型断言不是类型转换,断言成一个联合类型中不存在的类型是不允许的**

basics/type-of-function.md

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,8 @@ mySearch = function(source: string, subString: string) {
8585
}
8686
```
8787

88+
采用函数表达式|接口定义函数的方式时,对等号左侧进行类型限制,可以保证以后对函数名赋值时保证参数个数、参数类型、返回值类型不变。
89+
8890
## 可选参数
8991

9092
前面提到,输入多余的(或者少于要求的)参数,是不允许的。那么如何定义可选的参数呢?
@@ -154,7 +156,7 @@ function push(array, ...items) {
154156
});
155157
}
156158

157-
let a = [];
159+
let a: any[] = [];
158160
push(a, 1, 2, 3);
159161
```
160162

@@ -191,7 +193,7 @@ function reverse(x: number | string): number | string {
191193
}
192194
```
193195

194-
然而这样有一个缺点,就是不能够精确的表达,输入为数字的时候,输出也应该为数字,输入为字符串的时候,输出也应该为字符串。
196+
**然而这样有一个缺点,就是不能够精确的表达,输入为数字的时候,输出也应该为数字,输入为字符串的时候,输出也应该为字符串。**
195197

196198
这时,我们可以使用重载定义多个 `reverse` 的函数类型:
197199

basics/type-of-object-interfaces.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,21 @@ let tom: Person = {
154154

155155
另外,在报错信息中可以看出,此时 `{ name: 'Tom', age: 25, gender: 'male' }` 的类型被推断成了 `{ [x: string]: string | number; name: string; age: number; gender: string; }`,这是联合类型和接口的结合。
156156

157+
一个接口中只能定义一个任意属性。如果接口中有多个类型的属性,则可以在任意属性中使用联合类型:
158+
```ts
159+
interface Person {
160+
name: string;
161+
age?: number;
162+
[propName: string]: string | number;
163+
}
164+
165+
let tom: Person = {
166+
name: 'Tom',
167+
age: 25,
168+
gender: 'male'
169+
};
170+
```
171+
157172
## 只读属性
158173

159174
有时候我们希望对象中的一些字段只能在创建的时候被赋值,那么可以用 `readonly` 定义只读属性:

0 commit comments

Comments
 (0)