8.泛型.ts 886 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. (function(){
  2. // function fn1(x:string):string {
  3. // return x;
  4. // }
  5. // fn1('12');
  6. // 泛型:用字符去指代未知类型 具体的类型 使用时 在传值
  7. function fn1<T,K>(xxx:T,y:K):[T,K] {
  8. return [xxx,y];
  9. }
  10. // 当传入实参时 函数中的泛型会自动解析实参的类型
  11. // fn1(111);
  12. // fn1('tttt');
  13. // // 可以再传入参数时 直接声明类型 在<>内
  14. // fn1<Boolean>(true);
  15. // fn1('1',false);
  16. // fn1<string,boolean>('1',false);
  17. interface happy {
  18. jump: string
  19. }
  20. // 函数 泛型继承接口
  21. function fn2<T extends happy>(x:T):T {
  22. return x;
  23. }
  24. fn2({jump:'2'})
  25. //类 泛型继承接口
  26. class News<T extends happy> {
  27. xxx:T;
  28. constructor(x:T) {
  29. this.xxx = x;
  30. }
  31. }
  32. let news = new News({jump:'2'});
  33. })()