>[success] # extends 泛型約束
~~~
1.泛型現在似乎可以是任何類型,但實際開發可能往往不是任意類型,需要給以一個范圍,這種就叫'泛型約束'關鍵字('extends')
泛型是具有當前指定的屬性寫法上'<T extends xx>'
2.注意泛型約束是約束泛型的 在<> 這里寫
~~~
>[danger] ##### 泛型約束
~~~
1.限定了泛型入參只能是 number | string | boolean 的子集
~~~
~~~
function reflectSpecified<P extends number | string | boolean>(param: P):P {
return param;
}
reflectSpecified('string'); // ok
reflectSpecified(1); // ok
reflectSpecified(true); // ok
reflectSpecified(null); // ts(2345) 'null' 不能賦予類型 'number | string | boolean'
~~~
~~~
interface ReduxModelSpecified<State extends { id: number; name: string }> {
state: State
}
type ComputedReduxModel1 = ReduxModelSpecified<{ id: number; name: string; }>; // ok
type ComputedReduxModel2 = ReduxModelSpecified<{ id: number; name: string; age: number; }>; // ok
type ComputedReduxModel3 = ReduxModelSpecified<{ id: string; name: number; }>; // ts(2344)
type ComputedReduxModel4 = ReduxModelSpecified<{ id: number;}>; // ts(2344)
~~~
>[danger] ##### 泛型約束結合索引類型的使用
~~~
1.看下面案例想 獲取對象value 輸出出來
type Info = {
name:string
age:number
}
function getVal(obj:Info, key:any) {
return obj[key] // 報錯
}
~~~

* 正確寫法可以利用keyof 吧傳入的對象的屬性類型取出生成一個聯合類型
~~~
type Info = {
name:string
age:number
}
function getVal(obj:Info, key:keyof Info) {
return obj[key]
}
~~~
* 使用泛型
~~~
1.利用'索引類型 keyof T 把傳入的對象的屬性類型取出生成一個聯合類型',再用'extends 做約束'
~~~
~~~
// 注意泛型約束是約束泛型的 在<> 這里寫
type GetVal = <T extends object, K extends keyof T>(obj: T, key: K) => string
function getVal(obj: any, key: any): GetVal {
return obj[key]
}
getVal({ name: 'w' }, 'name')
~~~
>[danger] ##### 多重約束
~~~
interface FirstInterface {
doSomething(): number
}
interface SecondInterface {
doSomethingElse(): string
}
// // interface ChildInterface extends FirstInterface, SecondInterface {}
二者等同
class Demo<T extends FirstInterface & SecondInterface> {
private genericProperty: T
useT() {
this.genericProperty.doSomething() // ok
this.genericProperty.doSomethingElse() // ok
}
}
~~~
- TypeSprict -- 了解
- TS-- 搭建(一)webpack版本
- TS -- 搭建(二)直接使用
- TS -- 基本類型
- ts -- 類型推導和字面量類型
- ts -- 類型擴展和類型縮小
- ts -- any場景
- ts -- 使用unknown 還是 any
- ts -- any/never/unknown
- ts -- 斷言
- ts -- 類型大小寫疑惑
- ts -- 數組類型 [] 還是泛型疑惑
- TS -- 枚舉
- 外部枚舉
- TS -- 函數
- ts -- 重載作用
- ts -- 05 this is
- 解構
- TS -- 接口
- 繞過接口的多余參數檢查
- Interface 與 Type 的區別
- TS -- 類
- ts -- 類作為類型
- TS -- 交叉和聯合 類型
- ts -- 交叉類型
- ts -- 聯合類型
- ts -- 交叉和聯合優先級
- ts -- 類型縮減
- TS -- 什么是泛型
- ts -- 泛型函數表達式/函數別名/接口
- ts -- 泛型類
- ts -- extends 泛型約束
- ts -- 泛型new
- ts -- Ts的泛型
- TS -- 縮小類型詳解類型守衛
- TS -- 類型兼容性
- TS -- 命名空間與模塊化
- ts -- 模塊化
- ts -- 命名空間
- TS -- 工具方法
- Record -- 一組屬性 K(類型 T)
- Exclude -- 從聯合類型中去除指定的類
- Extract -- 聯合類型交集
- NonNullable -- 從聯合類型中去除 null 或者 undefined
- Partial -- 將所有屬性變為可選
- Required -- 所有屬性變為必填
- Readonly -- 所有屬性只讀
- Pick -- 類型中選取出指定的鍵值
- Omit -- 去除指定的鍵值