You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

32 lines
945 B

// 泛型约束的两种方式:1.指定更加具体的类型 2.添加约束
function id<Type>(value: Type) : Type {
// Type 是表示任意类型的,导致 value 没办法访问任何属性和方法
// console.log(value.length) // length 会报错
return value
}
// 第一种:指定更加具体的类型
// 将类型修改为 Type[] ( Type 类型的数组 ),因为只要是数组就一定存在 length 属性,所以可以访问
function id2<Type>(value: Type[]) : Type[] {
console.log(value.length)
return value
}
// 第二种:添加约束
interface ILength { length: number }
// 这里的 extends 不是继承,而是表示 Type 要满足 ILength 中 length 属性的约束
function id3 <Type extends ILength> (value: Type) : Type {
value.length
return value
}
// 只要满足 length 属性就可以
id3(['a', 'x'])
id3('abc')
id3({length: 10, name: 'jack'})
// 错误演示
// id3(123)