TypeScript学习笔记
function join<sdq>(one: sdq, two: sdq) { return `${one}${two}`;}join <string> ("我叫", "史迪奇");
// 定义数组function MyName<SDQ>(params: Array<SDQ>) { return params;}MyName <string> (["626", "626"]);
// 定义多个泛型function join<sdq, sdz>(one: sdq, two: sdz) { return `${one}${two}`;}join < number, string > (626, "626");
class Syp <sdq> { constructor(private syps: sdq[]) {} getSyp(index: number): sdq { return this.syps[index]; }}const syp = new Syp(["史迪奇", "鲁本", "安琪"]);console.log(syp.getSyp(1));
interface SDQ{ name:string;}// 继承SDQclass Syp <sdq extends SDQ> { constructor(private syps: sdq[]) {} getSyp(index: number): string { return this.syps[index].name; }}const syp = new Syp([ {name:"史迪奇"}, {name:"鲁本"}, {name:"安琪"}]);console.log(syp.getSyp(0));
// 约束: 要么是number要么是stringclass Syp <sdq extends number | string> { constructor(private syps: sdq[]) {} getSyp(index: number): sdq { return this.syps[index]; }}const syp = new Syp <string>(["史迪奇", "鲁本", "安琪"]);console.log(syp.getSyp(1));
作者: 我叫史迪奇本文来自于: https://sdq3.tk/TypeScript-genericity.html博客内容遵循 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 协议