| 12345678910111213141516171819202122232425262728293031323334353637383940 |
- (function () {
- // 泛型:先用字符去指代未知类型 使用时 传入具体的类型
- function fn3<T>(x: T): T {
- return x;
- }
- fn3(12);
- fn3<string>("12");
- // function fn4<T extends number | string, K extends number | string>(x: T, y: K): number | string {
- // return x + y;
- // }
- function fn4<T, K>(x: T, y: K): string | number {
- return (x as number) + (y as string)
- }
- function fn5<T, K>(x: T, y: K): [T, K] {
- return [x, y];
- }
- fn5(3, '43')
- const res = fn4(3, '23');
- console.log(res, '22222')
- interface happy {
- jump: string
- }
- // 严格按照接口格式传参
- // 函数中泛型继承接口
- function fn6<T extends happy>(a:T):T {
- return a;
- }
- fn6({jump: 'aa'})
- // 类中泛型继承接口
- class Ending<T extends happy>{
- name:T;
- constructor(name:T) {
- this.name = name;
- }
- }
- let e = new Ending({jump: 'aa'})
- })()
|