function firstElement < T >( arr : T []): T | undefined {
return arr [ 0 ]
}
firstElement < string >([ “hello” , “lihao” ])
firstElement < number >([ 1 , 2 , 3 ])
function map < I , O >( arr : I [], func 😦 arr : I ) => O ): O []{
return arr . map ( func )
}
// 把字符串转成 number 类型
const parsed = map ([ ‘1’ , ‘2’ , ‘3’ ],( n ) => { return parseInt ( n )})
console . log ( parsed )
// 泛型约束 extends
// 限制条件
// 限制了传的 A B 包含 length 属性
function longest < Type extends { length : number }>( a : Type , b : Type ){
if ( a . length >= b . length ){
return a
} else {
return b
}
}
// 泛型约束
// 在书写泛型的时候,我们往往需要对类型参数作一定的限制,比如希望传入的参数都有 name 属性的数组我们可以这么写:
function getCnames < T extends { name : string }>( entities : T []): string [] {
return entities . map ( entity => entity . name )
}
// 这里 extends 对传入的参数作了一个限制,就是 entities 的每一项可以是一个对象,
// 但是必须含有类型为 string 的 cname 属性。再比如,redux 里 dispatch 一个 action,必须包含 type 属性:
interface Dispatch < T extends { type : string }> {
( action : T ): T
}
// 条件类型与高阶类型
// SomeType extends OtherType ? TrueType : FalseType;
//extends 还有一大用途就是用来判断一个类型是不是可以分配给另一个类型,这在写高级类型的时候非常有用,举个????:
type Human = {
name : string ;
}
type Duck = {
name : string ;
}
type Bool = Duck extends Human ? ‘yes’ : ‘no’ ; // Bool => ‘yes’
// 指定类型参数
function combine < Type >( arr1 : Type [], arr2 : Type []): Type []{
return arr1 . concat ( arr2 )
}
// const arrCom=combine([1.2,3],[4,5,6])
// 指定参数的类型 比如 string numb
const arrCom = combine < string | number >([ ‘1’ , ‘2’ , ‘3’ ],[ 4 , 5 , 6 ])
// 优秀通用函数准则
// 尽量使用 T 泛型来约束,
function firsrELement < T >( arr : T []){
return arr [ 0 ]
}
function firstElement2 < T extends any []>( arr : T ){
return arr [ 0 ]
}
const a1 = firsrELement ([ 1 ])
const a2 = firstElement2 ([ 1 ])
// 尽可能少使用类型