泛型的使用场景和具体使用方法
[toc]
为什么要使用泛型如下情况(我们不知道对象的类型也,这样我们无法定义obj的类型也无法知道k的类型)
泛型函数
function getVal(obj,k){return obj[k];}
这个时候我们就可以使用到了泛型,我们可以定义一个泛型参数在调用函数的时候传入泛型参数就可以了
function getVal<T>(obj:T,k:keyof T){return obj[T]}//调用的时候let obj1={name:"Ass",age:23,gender:"male"}let result =getVal<typeof obj1>(obj1,"name");
所谓的泛型就是给可变(不定)的类型定义变量(参数),<>类似()
泛型类
就像基于react的模拟组件
abstract class Component<T1, T2> {props: T1;state: T2;constructor(props: T1) {this.props = props;}abstract render(): string;}interface IMyComponentProps {val: number;}interface IMyComponentState {x: number; }class MyComponent extends Component<IMyComponentProps, IMyComponentState> {constructor(props: IMyComponentProps) {super(props);this.state = {x: 1} }render() {this.props.val;this.state.x;return '<myComponent />';}}let myComponent = new MyComponent({val: 1});myComponent.render();
泛型接口
我们可以在接口中使用泛型
后端提供了一些接口,用以返回一些数据,依据返回的数据格式定义如下接口
interface IResponseData{code:number;message?:string;data:any;}//根据接口我们可以封装对应的一些方法function getData(url:string){return fetch(url).then(res=>res.json).then((data:IResponseData)=>data);}//这个时候我们发现请求不同接口的时候IResponseData里面的data的数据类型是any类型,这个时候我们希望请求不同接口的时候,data数据是确定的,那么这个时候我们再对IResponseData使用泛型interface IResponseData<T>{code:number;message?:string;data:T;}//在函数定义的时候function getData<U>(url:string){return fetch(url).then(res=>res.json).then((data:IResponseData<U>)=>data)}//这时候我们就可以定义不同的接口来实现定义后端返回的不同的数据了// 用户接口interface IResponseUserData {id: number;username: string;email: string;}// 文章接口interface IResponseArticleData {id: number;title: string;author: IResponseUserData;}//调用~(async function(){let user = await getData<IResponseUserData>('');if (user.code === 1) {console.log(user.message);} else {console.log(user.data.username);}let articles = await getData<IResponseArticleData>('');if (articles.code === 1) {console.log(articles.message);} else {console.log(articles.data.id);console.log(articles.data.author.username);}});
