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.

31 lines
945 B

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