TypeScript : typeof的使用场景之一

2022-07-13  本文已影响0人  这个超人不会飞阿

我们先来看下以下代码

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> 解决

上一篇 下一篇

猜你喜欢

热点阅读