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 {
156156
157157let createArray: CreateArrayFunc ;
158158createArray = 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
176176let createArray: CreateArrayFunc <any >;
177177createArray = 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;
202202myGenericNumber .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 ) )
You can’t perform that action at this time.
0 commit comments