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

Skip to content

Commit 85f5da4

Browse files
committed
add default type params of generics
1 parent b834a32 commit 85f5da4

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

advanced/generics.md

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ interface CreateArrayFunc {
156156

157157
let createArray: CreateArrayFunc;
158158
createArray = function<T>(length: number, value: T): Array<T> {
159-
let result = [];
159+
let result: T[] = [];
160160
for (let i = 0; i < length; i++) {
161161
result[i] = value;
162162
}
@@ -175,7 +175,7 @@ interface CreateArrayFunc<T> {
175175

176176
let createArray: CreateArrayFunc<any>;
177177
createArray = function<T>(length: number, value: T): Array<T> {
178-
let result = [];
178+
let result: T[] = [];
179179
for (let i = 0; i < length; i++) {
180180
result[i] = value;
181181
}
@@ -202,6 +202,20 @@ myGenericNumber.zeroValue = 0;
202202
myGenericNumber.add = function(x, y) { return x + y; };
203203
```
204204

205+
## 类型参数的默认类型
206+
207+
在 TypeScript 2.3 以后,我们可以为泛型中的类型参数指定默认类型。当使用泛型时没有在代码中直接指定类型参数,从实际 (值) 参数中也无法推测出时,这个默认类型会起作用。
208+
209+
```ts
210+
function foo<T = number>(e?: T[]): T[] {
211+
return (e ? e : []) as T[];
212+
}
213+
214+
const specified: string[] = foo<string>([]);
215+
const inferred: string[] = foo([""]);
216+
const default_used: number[] = foo();
217+
```
218+
205219
## 参考
206220

207221
- [Generics](http://www.typescriptlang.org/docs/handbook/generics.html)[中文版](https://zhongsp.gitbooks.io/typescript-handbook/content/doc/handbook/generics.html)

0 commit comments

Comments
 (0)