<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                # 泛型 泛型(Generics)是指在定義函數、接口或類的時候,不預先指定具體的類型,而在使用的時候再指定類型的一種特性。 ## 簡單的例子 首先,我們來實現一個函數 `createArray`,它可以創建一個指定長度的數組,同時將每一項都填充一個默認值: ```ts function createArray(length: number, value: any): Array<any> { let result = []; for (let i = 0; i < length; i++) { result[i] = value; } return result; } createArray(3, 'x'); // ['x', 'x', 'x'] ``` 上例中,我們使用了[之前提到過的數組泛型](../basics/type-of-array.md#數組泛型)來定義返回值的類型。 這段代碼編譯不會報錯,但是一個顯而易見的缺陷是,它并沒有準確的定義返回值的類型: `Array<any>` 允許數組的每一項都為任意類型。但是我們預期的是,數組中每一項都應該是輸入的 `value` 的類型。 這時候,泛型就派上用場了: ```ts function createArray<T>(length: number, value: T): Array<T> { ? let result: T[] = []; for (let i = 0; i < length; i++) { result[i] = value; } return result; } createArray<string>(3, 'x'); // ['x', 'x', 'x'] ``` 上例中,我們在函數名后添加了 `<T>`,其中 `T` 用來指代任意輸入的類型,在后面的輸入 `value: T` 和輸出 `Array<T>` 中即可使用了。 接著在調用的時候,可以指定它具體的類型為 `string`。當然,也可以不手動指定,而讓類型推論自動推算出來: ```ts function createArray<T>(length: number, value: T): Array<T> { let result: T[] = []; for (let i = 0; i < length; i++) { result[i] = value; } return result; } createArray(3, 'x'); // ['x', 'x', 'x'] ``` ## 多個類型參數 定義泛型的時候,可以一次定義多個類型參數: ```ts function swap<T, U>(tuple: [T, U]): [U, T] { return [tuple[1], tuple[0]]; } swap([7, 'seven']); // ['seven', 7] ``` 上例中,我們定義了一個 `swap` 函數,用來交換輸入的元組。 ## 泛型約束 在函數內部使用泛型變量的時候,由于事先不知道它是哪種類型,所以不能隨意的操作它的屬性或方法: ```ts function loggingIdentity<T>(arg: T): T { console.log(arg.length); return arg; } // index.ts(2,19): error TS2339: Property 'length' does not exist on type 'T'. ``` 上例中,泛型 `T` 不一定包含屬性 `length`,所以編譯的時候報錯了。 這時,我們可以對泛型進行約束,只允許這個函數傳入那些包含 `length` 屬性的變量。這就是泛型約束: ```ts interface Lengthwise { length: number; } function loggingIdentity<T extends Lengthwise>(arg: T): T { console.log(arg.length); return arg; } ``` 上例中,我們使用了 `extends` 約束了泛型 `T` 必須符合接口 `Lengthwise` 的形狀,也就是必須包含 `length` 屬性。 此時如果調用 `loggingIdentity` 的時候,傳入的 `arg` 不包含 `length`,那么在編譯階段就會報錯了: ```ts interface Lengthwise { length: number; } function loggingIdentity<T extends Lengthwise>(arg: T): T { console.log(arg.length); return arg; } loggingIdentity(7); // index.ts(10,17): error TS2345: Argument of type '7' is not assignable to parameter of type 'Lengthwise'. ``` 多個類型參數之間也可以互相約束: ```ts function copyFields<T extends U, U>(target: T, source: U): T { for (let id in source) { target[id] = (<T>source)[id]; } return target; } let x = { a: 1, b: 2, c: 3, d: 4 }; copyFields(x, { b: 10, d: 20 }); ``` 上例中,我們使用了兩個類型參數,其中要求 `T` 繼承 `U`,這樣就保證了 `U` 上不會出現 `T` 中不存在的字段。 ## 泛型接口 [之前學習過](../basics/type-of-function.md#接口中函數的定義),可以使用接口的方式來定義一個函數需要符合的形狀: ```ts interface SearchFunc { (source: string, subString: string): boolean; } let mySearch: SearchFunc; mySearch = function(source: string, subString: string) { return source.search(subString) !== -1; } ``` 當然也可以使用含有泛型的接口來定義函數的形狀: ```ts interface CreateArrayFunc { <T>(length: number, value: T): Array<T>; } let createArray: CreateArrayFunc; createArray = function<T>(length: number, value: T): Array<T> { let result: T[] = []; for (let i = 0; i < length; i++) { result[i] = value; } return result; } createArray(3, 'x'); // ['x', 'x', 'x'] ``` 進一步,我們可以把泛型參數提前到接口名上: ```ts interface CreateArrayFunc<T> { (length: number, value: T): Array<T>; } let createArray: CreateArrayFunc<any>; createArray = function<T>(length: number, value: T): Array<T> { let result: T[] = []; for (let i = 0; i < length; i++) { result[i] = value; } return result; } createArray(3, 'x'); // ['x', 'x', 'x'] ``` 注意,此時在使用泛型接口的時候,需要定義泛型的類型。 ## 泛型類 與泛型接口類似,泛型也可以用于類的類型定義中: ```ts class GenericNumber<T> { zeroValue: T; add: (x: T, y: T) => T; } let myGenericNumber = new GenericNumber<number>(); myGenericNumber.zeroValue = 0; myGenericNumber.add = function(x, y) { return x + y; }; ``` ## 泛型參數的默認類型 在 TypeScript 2.3 以后,我們可以為泛型中的類型參數指定默認類型。當使用泛型時沒有在代碼中直接指定類型參數,從實際值參數中也無法推測出時,這個默認類型就會起作用。 ```ts function createArray<T = string>(length: number, value: T): Array<T> { let result: T[] = []; for (let i = 0; i < length; i++) { result[i] = value; } return result; } ``` ## 參考 - [Generics](http://www.typescriptlang.org/docs/handbook/generics.html)([中文版](https://zhongsp.gitbooks.io/typescript-handbook/content/doc/handbook/generics.html)) - [Generic parameter defaults](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-3.html#generic-parameter-defaults) --- - [上一章:類與接口](class-and-interfaces.md) - [下一章:聲明合并](declaration-merging.md)
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看