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

Skip to content

Commit a3d76f4

Browse files
authored
更新泛型参数的默认类型
1 parent 85f5da4 commit a3d76f4

File tree

1 file changed

+11
-10
lines changed

1 file changed

+11
-10
lines changed

advanced/generics.md

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ createArray(3, 'x'); // ['x', 'x', 'x']
2828

2929
```ts
3030
function createArray<T>(length: number, value: T): Array<T> {
31-
let result = [];
31+
 let result: T[] = [];
3232
for (let i = 0; i < length; i++) {
3333
result[i] = value;
3434
}
@@ -44,7 +44,7 @@ createArray<string>(3, 'x'); // ['x', 'x', 'x']
4444

4545
```ts
4646
function createArray<T>(length: number, value: T): Array<T> {
47-
let result = [];
47+
let result: T[] = [];
4848
for (let i = 0; i < length; i++) {
4949
result[i] = value;
5050
}
@@ -202,23 +202,24 @@ myGenericNumber.zeroValue = 0;
202202
myGenericNumber.add = function(x, y) { return x + y; };
203203
```
204204

205-
## 类型参数的默认类型
205+
## 泛型参数的默认类型
206206

207-
在 TypeScript 2.3 以后,我们可以为泛型中的类型参数指定默认类型。当使用泛型时没有在代码中直接指定类型参数,从实际 (值) 参数中也无法推测出时,这个默认类型会起作用
207+
在 TypeScript 2.3 以后,我们可以为泛型中的类型参数指定默认类型。当使用泛型时没有在代码中直接指定类型参数,从实际值参数中也无法推测出时,这个默认类型就会起作用
208208

209209
```ts
210-
function foo<T = number>(e?: T[]): T[] {
211-
return (e ? e : []) as T[];
210+
function createArray<T = string>(length: number, value: T): Array<T> {
211+
let result: T[] = [];
212+
for (let i = 0; i < length; i++) {
213+
result[i] = value;
214+
}
215+
return result;
212216
}
213-
214-
const specified: string[] = foo<string>([]);
215-
const inferred: string[] = foo([""]);
216-
const default_used: number[] = foo();
217217
```
218218

219219
## 参考
220220

221221
- [Generics](http://www.typescriptlang.org/docs/handbook/generics.html)[中文版](https://zhongsp.gitbooks.io/typescript-handbook/content/doc/handbook/generics.html)
222+
- [Generic parameter defaults](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-3.html#generic-parameter-defaults)
222223

223224
---
224225

0 commit comments

Comments
 (0)