跳到主要内容

泛型入門

什麼是泛型?

泛型的英文是Generics,是指在定義方法、介面或類的時候,不預先指定具體的型別,而使用的時候再指定一個型別的一個特性。

泛型命名

泛型一些約定俗成的命名(實際並無意義,但是建議對應著來命名泛型):

  • E - Element
  • K - Key
  • N - Number
  • T - Type
  • V - Value
  • S,U,V etc. - 2nd, 3rd, 4th types

演進範例

一個可接受任何值的 function

// Declare a regular function
function regularFunc(x: any) {
// You can use x here
}
// Call it: x will be 1
regularFunc(1)

可聲明型別為number的泛型函式

// Declare a generic function
function genericFunc<T>() {
// You can use T here
}
// Call it: T will be number
genericFunc<number>()

一個只接受number 的 function

// Specify x to be number
function regularFunc(x: number)
// Success
regularFunc(1)
// Error
regularFunc('foo')

限定聲明型別為number的泛型函式

// Limits the type of T
function genericFunc<T extends number>()
// Success
genericFunc<number>()
// Error
genericFunc<string>()

預設值為2的 function

// Set the default value of x
function regularFunc(x = 2)
// x will be 2 inside the function
regularFunc()

預設型別為number的泛型函式

// Set the default type of T
function genericFunc<T = number>()
// T will be number inside the function
genericFunc()

多參數的複雜範例

// The second parameter S must be either
// boolean or whatever was specified for F
function makePair<
F extends number | string,
S extends boolean | F
>()
// These will work
makePair<number, boolean>()
makePair<number, number>()
makePair<string, boolean>()
makePair<string, string>()
// This will fail because the second
// parameter must extend boolean | number,
// but instead it’s string
makePair<number, string>()

參考資料