7.泛型.ts 997 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. (function () {
  2. // 泛型:先用字符去指代未知类型 使用时 传入具体的类型
  3. function fn3<T>(x: T): T {
  4. return x;
  5. }
  6. fn3(12);
  7. fn3<string>("12");
  8. // function fn4<T extends number | string, K extends number | string>(x: T, y: K): number | string {
  9. // return x + y;
  10. // }
  11. function fn4<T, K>(x: T, y: K): string | number {
  12. return (x as number) + (y as string)
  13. }
  14. function fn5<T, K>(x: T, y: K): [T, K] {
  15. return [x, y];
  16. }
  17. fn5(3, '43')
  18. const res = fn4(3, '23');
  19. console.log(res, '22222')
  20. interface happy {
  21. jump: string
  22. }
  23. // 严格按照接口格式传参
  24. // 函数中泛型继承接口
  25. function fn6<T extends happy>(a:T):T {
  26. return a;
  27. }
  28. fn6({jump: 'aa'})
  29. // 类中泛型继承接口
  30. class Ending<T extends happy>{
  31. name:T;
  32. constructor(name:T) {
  33. this.name = name;
  34. }
  35. }
  36. let e = new Ending({jump: 'aa'})
  37. })()