TypeScript 泛型
一、概念
在定义函数、类、接口时,使用类型参数来表示未指定的类型,在使用时,指定具体的类型
二、函数
1、单个泛型
// 在定义函数时,用类型参数,代表类型,在具体使用是指定具体类型 function printData<T>(data:T):T{ console.log(data); return data } console.log(printData<string>("Hello")); console.log(printData<number>(100));
2、多个泛型
// 多个泛型 function introduce<T, K>(name:T, age:K): void{ console.log(`我是${name},我今年${age}`); } introduce<string,number>("jojo", 8) introduce<number, boolean>(18, true)
三、类
class Person<T, K>{ constructor(public name:T, public age:K, public sex:T){} } let p1 = new Person<string, number>("jojo", 10, "男") console.log(p1.name);
四、接口
1、普通类型
interface InfoInterface<T>{ name:string, age:number, extrInfo:T } let p1:InfoInterface<string> p1={ name:'tt', age:8, extrInfo:'王侯将相,宁有种乎' } let p2:InfoInterface<number> console.log(p1); p2={ name:'pp', age:9527, extrInfo:1234 } console.log(p2);
2、type定义类型
interface PersonInterface<T>{ name:string, age:number, extra:T } type JobInfo={ post:string, money:number } let p1:PersonInterface<JobInfo> p1 = { name:"阿三", age:99, extra:{ post:"拾大粪", money:-100 } } console.log(p1.extra);