TypeScript : typeof的使用场景之一

我们先来看下以下代码

export const http = async (endpoint: string, { data, token, headers, ...customConfig }: Config) => {
    // xxx
    // xxx
}

export const useHttp = () => {
  // 这里可以优化的地方 [string, Config] 这个类型其实与我们定义的函数http的类型是一模一样的
  // 有没有一种方法让我们直接从http函数获取的入参的类型,而不是需要重复写一遍
  // 有呀,那就是通过 Parameters<typeof http> 来解决,拿到http的类型
  return ([endpoint, config]: [string, Config]) => {
    // xxx
  }

}

我们看到的上面的代码,以及注释,我们的目的就是想快速拿到函数http入参的TS类型,解决方案如下

export const useHttp = () => {
  const { user } = useAuth()

  // 这里可以优化的地方 [string, Config] 这个类型其实与我们定义的函数http的类型是一模一样的
  // 有没有一种方法让我们直接从http函数获取的入参的类型,而不是需要重复写一遍
  // 有呀,那就是通过 Parameters<typeof http> 来解决,拿到http的类型
  // return ([endpoint, config]: [string, Config]) => {
  //   http(endpoint, { ...config, token: user?.token })
  // }

  return ([endpoint, config]: Parameters<typeof http>) => {
    http(endpoint, { ...config, token: user?.token })
  }
}

使用Parameters<typeof http> 解决

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容