File tree Expand file tree Collapse file tree 1 file changed +16
-2
lines changed Expand file tree Collapse file tree 1 file changed +16
-2
lines changed Original file line number Diff line number Diff line change @@ -156,7 +156,7 @@ interface CreateArrayFunc {
156
156
157
157
let createArray: CreateArrayFunc ;
158
158
createArray = function <T >(length : number , value : T ): Array <T > {
159
- let result = [];
159
+ let result: T [] = [];
160
160
for (let i = 0 ; i < length ; i ++ ) {
161
161
result [i ] = value ;
162
162
}
@@ -175,7 +175,7 @@ interface CreateArrayFunc<T> {
175
175
176
176
let createArray: CreateArrayFunc <any >;
177
177
createArray = function <T >(length : number , value : T ): Array <T > {
178
- let result = [];
178
+ let result: T [] = [];
179
179
for (let i = 0 ; i < length ; i ++ ) {
180
180
result [i ] = value ;
181
181
}
@@ -202,6 +202,20 @@ myGenericNumber.zeroValue = 0;
202
202
myGenericNumber .add = function (x , y ) { return x + y ; };
203
203
```
204
204
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
+
205
219
## 参考
206
220
207
221
- [ Generics] ( http://www.typescriptlang.org/docs/handbook/generics.html ) ([ 中文版] ( https://zhongsp.gitbooks.io/typescript-handbook/content/doc/handbook/generics.html ) )
You can’t perform that action at this time.
0 commit comments