您当前的位置: 首页 >  ar

暂无认证

  • 0浏览

    0关注

    92582博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

typescript中的泛型(genericParadigm)、interface、extends、constructor

发布时间:2022-01-04 22:18:52 ,浏览量:0

function fnAny(a: any): any { return a; } console.log('number:', fnAny(10)); // number: 10 console.log('string:', fnAny('半晨')); // string: 半晨 // 在定义函数或是类时,如果遇到类型不明确就可以使用泛型 // T是任意字母,只是个代表而已,也就是变量的意思 function fn<T>(a: T): T { return a; } // 可以直接调用具有泛型的函数 // 不指定泛型,TS可以自动对类型进行推断 console.log('number:', fn(24)); // number: 24 // 指定泛型 console.log('string:', fn<string>('hello')); // string: hello // 泛型可以同时指定多个 function fn2<T, K>(a: T, b: K): T { console.log('b:', b); // b: hello return a; } console.log('a:', fn2<number, string>(123, 'hello')); // a: 123 // 接口 interface Inter { length: number; } // T extends Inter 表示泛型T必须是Inter的实现类(子类) function fn3<T extends Inter>(a: T): number { return a.length; } class MyClass<T>{ name: T; constructor(name: T) { this.name = name; console.log('name:', this.name); // name: 半晨 } } new MyClass<string>('半晨'); 
关注
打赏
1653961664
查看更多评论
立即登录/注册

微信扫码登录

0.5629s