如何理解泛型
泛型(Generic Type)存在于許多編程語言中,許多剛接觸Typescript且沒有Java、C++等帶泛型的語言使用經驗的程序員,理解起來會有一定的難度,特此開文掃盲
我們再來定義一個盒子box,盒子有number類型的id,而data是任意類型,你可能會想到any
interface Box {
id: number,
data: any
}
然而any一時爽,對后期的閱讀和分析大為不利。
來看看使用泛型的方式,只要在頭部使用尖括號<T>,代碼塊中使用T來表示類型即可:
interface Box<T> {
id: number,
data: T
}
使用帶有泛型的Box的時候,我們再傳入具體的值:
const box1: Box<string> = {
id: 1,
data: 'this is string box'
}
const box2: Box<boolean> = {
id: 2,
data: false
}
我們類比一個函數:
function square(a) {
return a*a
}
上面的泛型<T>,類似于square函數中的形參a, 定義時用來表示寬泛、不確定的值(類型),使用的時候再傳入具體的值(類型)
sum(4) // 16
我們可以將泛型理解為: 參數化的類型
有了泛型,我們可以更加具體地描述一個不確定的類型。與any相比,泛型更具有約束力。
泛型的具體用法
上面提到了interface使用泛型的方法,下面將會介紹泛型的其他應用場景
在function/type/class中使用泛型:
泛型可以在function/type/class中聲明。
還是以Box舉例,type的泛型長得跟interface的基本一樣
type Box<B> {
id: number,
value: B
}
寫一個函數,讓一個值變成Box類型:
function toBox<B>(value: B) {
return {
id: new Date().getTime(),
value: value
}
}
const box3: Box<string> = toBox('string box')
const box4: Box<number[]> = toBox([1,2,3,4,5])
寫一個class,把這個Box用class封裝起來:
class MyBox<B> {
private id: number;
private value: B;
public static from<B> (value: B) {
return new MyBox(value)
}
constructor () {
this.id = new Date().getTime();
this.value = value;
}
// 只允許修改成相同類型的value
public setValue(value: B): void {
this.value = value;
}
public getValue(): B {
return this.value;
}
}
定義多個泛型
這次我們定義一個抽屜,抽屜有三層,三層可以放三種數據
type Drawer<L1, L2, L3> = [L1, L2, L3];
const myDrawer<string, string, string> = ['香煙', '茶葉', '啤酒']
如果一個React項目使用了TypeScript,那么組件可以接受Props泛型和State泛型
type CountProps = {
initValue: number,
step?: number
}
type CountState = {
value: number
}
class Counter extends React.component<CountProps, CountState> {
constructor(props) {
super(props)
this.state = {
value: props.initValue || 0
}
}
// 以下略
}
默認泛型
如果某個泛型有默認值,使用的時候不傳入類型即為默認值:
type Box<S = string> {
id: number,
value: S
}
var boxDefault: Box = { id: 6, value: 'default generic' }
var boxNumber: Box<number> = { id: 7, value: 3.1416 }
原生泛型的應用
Array
這個是最好理解的了,如果想定義一個類型固定的數組除了type[]外還可以使用泛型的方式:
const bools: Array<boolean> = [true, false, true, true, true]
const queue = Array<{id: number, value: string }> = [
{ id: 1, value: 'a' },
{ id: 2, value: 'b' },
{ id: 3, value: 'c' },
]
與type[]相比,如果定義一個帶有鍵值類型的數組,使用Array泛型可讀性會更高
Set和Map
const plants: Set<string> = new Set()
fruits.add('豌豆射手')
fruits.add('向日葵')
fruits.add('西瓜投手')
fruits.add('玉米大炮')
const subject: Map<string, number> = new Map()
subject.add('語文', 91)
subject.add('數學', 100)
subject.add('英語', 92)
subject.add('政治', 96)
Promise
type UserData = {
id: number,
name: string,
age: number
}
function fetchData(): Promise<UserData> {
return fetch('/userData').then(res => res.json())
}
async function fetchFollowList (): Promise<UserData> {
const { id } = await fetchData();
return fetch(`/follows/${id}`).then(res => res.json())
}