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.

16 lines
433 B

2 years ago
  1. // 使用泛型创建一个函数
  2. function id<Type>(value: Type) : Type { // <Type> 相当于是一个占位符
  3. return value
  4. }
  5. // 调用泛型函数:
  6. // 1.以 number 类型调用泛型函数
  7. const num = id<number>(10)
  8. // 2.以 string 类型调用泛型函数
  9. const str = id<string>('a')
  10. const ret = id<boolean>(false)
  11. // 泛型简写
  12. let num1 = id(100) // number类型
  13. let str1 = id('abc') // string类型