泛型的使用场景和具体使用方法

[toc]

为什么要使用泛型如下情况(我们不知道对象的类型也,这样我们无法定义obj的类型也无法知道k的类型)

泛型函数

  1. function getVal(obj,k){
  2. return obj[k];
  3. }

这个时候我们就可以使用到了泛型,我们可以定义一个泛型参数在调用函数的时候传入泛型参数就可以了

  1. function getVal<T>(obj:T,k:keyof T){
  2. return obj[T]
  3. }
  4. //调用的时候
  5. let obj1={
  6. name:"Ass",
  7. age:23,
  8. gender:"male"
  9. }
  10. let result =getVal<typeof obj1>(obj1,"name");

所谓的泛型就是给可变(不定)的类型定义变量(参数),<>类似()

泛型类

就像基于react的模拟组件

  1. abstract class Component<T1, T2> {
  2. props: T1;
  3. state: T2;
  4. constructor(props: T1) {
  5. this.props = props;
  6. }
  7. abstract render(): string;
  8. }
  9. interface IMyComponentProps {
  10. val: number;
  11. }
  12. interface IMyComponentState {
  13. x: number; }
  14. class MyComponent extends Component<IMyComponentProps, IMyComponentState> {
  15. constructor(props: IMyComponentProps) {
  16. super(props);
  17. this.state = {
  18. x: 1
  19. } }
  20. render() {
  21. this.props.val;
  22. this.state.x;
  23. return '<myComponent />';
  24. }
  25. }
  26. let myComponent = new MyComponent({val: 1});
  27. myComponent.render();

泛型接口

我们可以在接口中使用泛型
后端提供了一些接口,用以返回一些数据,依据返回的数据格式定义如下接口

  1. interface IResponseData{
  2. code:number;
  3. message?:string;
  4. data:any;
  5. }
  6. //根据接口我们可以封装对应的一些方法
  7. function getDataurl:string){
  8. return fetch(url).then(res=>res.json).then((data:IResponseData)=>data);
  9. }
  10. //这个时候我们发现请求不同接口的时候IResponseData里面的data的数据类型是any类型,这个时候我们希望请求不同接口的时候,data数据是确定的,那么这个时候我们再对IResponseData使用泛型
  11. interface IResponseData<T>{
  12. code:number;
  13. message?:string;
  14. data:T;
  15. }
  16. //在函数定义的时候
  17. function getData<U>(url:string){
  18. return fetch(url).then(res=>res.json).then((data:IResponseData<U>)=>data)
  19. }
  20. //这时候我们就可以定义不同的接口来实现定义后端返回的不同的数据了
  21. // 用户接口
  22. interface IResponseUserData {
  23. id: number;
  24. username: string;
  25. email: string;
  26. }
  27. // 文章接口
  28. interface IResponseArticleData {
  29. id: number;
  30. title: string;
  31. author: IResponseUserData;
  32. }
  33. //调用
  34. ~(async function(){
  35. let user = await getData<IResponseUserData>('');
  36. if (user.code === 1) {
  37. console.log(user.message);
  38. } else {
  39. console.log(user.data.username);
  40. }
  41. let articles = await getData<IResponseArticleData>('');
  42. if (articles.code === 1) {
  43. console.log(articles.message);
  44. } else {
  45. console.log(articles.data.id);
  46. console.log(articles.data.author.username);
  47. }
  48. });