likes
comments
collection
share

TS 处理接口返回数据

作者站长头像
站长
· 阅读数 31

写在前面

TypeScript 项目中,TypeScript 对接口返回数据的处理,是日常项目开发中一个比较棘手的问题。

那我们该如何 高效 的解决这个问题呢?

问题

项目中使用 ts 都会碰到如下场景:从接口请求过来的数据该如何进行处理?

const fetchInfo = async (url: string, id: string) => {
  return $http.get(url, params);
}

const res = await fetchInfo('/info', '886');

// 假设 `/info` 接口返回如下数据
{ id: '886', 🙈:{ name: 'Jack', 📱: { brand: 'Chinese Pineapple' } } }

那我们该如何得到 🙈 的名字以及使用的 📱 品牌呢?

解答

目前比较常用的写法有以下两种

  1. any 大法:

    const res:any = await fetchInfo('/info', '886');
    console.log(res.🙈.name) // Jack
    console.log(res.🙈.age)  // 3
    
  2. 更加优雅的 interface 写法:

    /** 根据接口返回的数据,声明对应的 interface **/
    interface Info {
      id: string;
      🙈: Monkey;
    }
    
    interface Monkey {
      name: string;
      📱: Phone;
    }
    
    interface Phone {
      brand: string;
    }
    
    /** 改写 `fetchInfo` 函数返回值类型 **/
    const fetchInfo = async (url: string, id: string): Promise<Info> => {
      return $http.get(url, params);
    }
    const res = await fetchInfo('/info', '886');
    console.log(res.🙈.name) // Jack
    console.log(res.🙈.age)  // 3
    

区别

两种实现方式的区别十分明显:

  1. any 大法

    • ✨ 前期开发代码量少,快速简单。
    • 🚨 由于未定义 interface 导致整个项目充斥着大量 any 类型,项目沦为 AnyScript
    • 🚨 无法获得健全的 ts 语法检测功能,弱化了使用 ts 的作用。
    • 🚨 后期维护成本高,后端修改字段,ts 语法无法检测。
  2. interface

    • 🚨 前期开发代码量大,需要为每个接口定义 interface
    • ✨ 获得丰富的代码提示以及语法检测能力。
    • ✨ 后期项目易维护,接口字段改动,只需要同步更新 interface 数据即可实现类型检测。

总结

通过上面的总结不难看出,interface 方式优势众多,但同时也有着一个致命的弊端:

我们在前期的开发过程中需要对所有接口返回的不同数据类型定义对应的 interface

例如上面示例的 /info 接口我们就需要定义三个 interface ,实际项目中,字段数量可能达到几十上百个!

interface Info {
  id: string;
  🙈: Monkey;
}

interface Monkey {
  name: string;
  📱: Phone;
}

interface Phone {
  brand: string;
}

这对于我们前期开发效率来说无疑是 毁灭性 的💥💥💥

🚀 必备高效神器

基于上面 interface 方式所面临的问题

给大家安利一款前端在线代码生成工具:JsonToAnyGitee / GitHub

能够很轻松的将我们接口返回的 JSON 数据转换成我们前端所需要的 interface

最大限度的节省了我们手动定义 interface 的时间

TS  处理接口返回数据

至此,我们完美解决的了 interface 方式最大的弊端,一劳永逸🎉。

转载自:https://juejin.cn/post/7184711253867102264
评论
请登录