上一章传送门
传送门:TypeScript快速入门(三)
一、泛型是什么?
在TypeScript中,泛型是一种创建可复用代码组件的工具。这种组件不只能被一种类型使用,而是能被多种类型复用。类似于参数的作用,泛型是一种用以增强类(classes)、类型(types)和接口(interfaces)能力的非常可靠的手段
二、函数泛型
1.初始泛型概念
泛型的定义使用<>(尖角号)进行定义的,比如现在给join方法一个泛型
function join<T>(first:T,second:T) {
return `${first}${second}`;
}
join<string>("hello,","world");
join<number>(1,2);
2.泛型中数组的使用
代码如下(示例):
function myFun<T>(params:T[]) {
return params;
}
console.log(myFun<string>(["111","222"]))
3.多个泛型的定义
这里定义了两个泛型T,P; 两个以上以此类推; 需要注意的是,如果函数定义了多个泛型,那么使用时要对应的定义出具体的类型
function join<T,P>(first:T,second:P) {
return `${first}${second}`;
}
join<string,number>("hello,",1);
join("hello",1);
三、TypeScript类中泛型
1.类的泛型
class selectGame <T>{
constructor(private games:T[]) {}
getGame(index:number):T{
return this.games[index]
}
}
const selectgame = new selectGame(["DNF","LOL","CF"])
console.log(selectgame.getGame(1))
2.泛型中类的继承
interface Game{
name:string
}
class selectGame<T extends Game>{
constructor(private games:T[]) { }
getGame(index:number):string{
return this.games[index].name
}
}
const selectgame = new selectGame([
{name:"DNF"},
{name:"LOL"},
{name:"CF"},
])
console.log(selectgame.getGame(1))
3.泛型约束
泛型约束顾名思义就是限定泛型所接受的类型范围 下面的例子:将泛型约束为number 以及 string
class selectGame <T extends number | string>{
constructor(private games:T[]) {}
getGame(index:number):T{
return this.games[index]
}
}
const selectgame = new selectGame<string>(["DNF","LOL","CF"])
console.log(selectgame.getGame(1))
总结
TypeScript的语法以及基本知识点已经学完了,作为javascript的超集,TypeScript的使用目前已经遍布前端各个框架,学习之后,需要在实际工作中不断精进,自行领悟。
|