标签:number this 函数 class log ons fun rip function
function join<T, P>(first: T, second: P) {
return `${first}${second}`;
}
// 泛型虽然可以类型推断,但是还是建议明确写明类型。
join < number, string > (1, "2");
// 数组的形式
// 1. 使用 []
function myFun<T>(params: T[]) {
return params;
}
myFun < string > ["123", "456"];
// 2. 使用 Array
function myFun<T>(params: Array<T>) {
return params;
}
myFun < string > ["123", "456"];
class SelectGirl<T> {
constructor(private girls: T[]) {}
getGirl(index: number): T {
return this.girls[index];
}
}
const selectGirl = new SelectGirl<string>(["大脚", "刘英", "晓红"]);
console.log(selectGirl.getGirl(1));
类型约束
class SelectGirl<T extends number | string> {
//.....
}
继承
interface Girl {
name: string;
}
class SelectGirl<T extends Girl> {
constructor(private girls: T[]) {}
getGirl(index: number): string {
return this.girls[index].name;
}
}
const selectGirl = new SelectGirl([
{ name: "大脚" },
{ name: "刘英" },
{ name: "晓红" },
]);
console.log(selectGirl.getGirl(1));
参考:
技术胖——TypeScript从入门到精通(20. TypeScript 函数泛型-难点)
技术胖——TypeScript从入门到精通(21. TypeScript 类中泛型-难点)
标签:number this 函数 class log ons fun rip function
原文地址:https://www.cnblogs.com/xch-jiang/p/14260119.html