const 函数、重载和泛型打字稿

2024-04-12

Typescript 支持函数重载,这非常酷,并且可以像这样重载常量函数:

interface FetchOverload {
  (action: string, method: 'post' | 'get'): object;
  (action: string): object
}

const fetch: FetchOverload = (action: string, method: 'get' | 'post' = 'get'): object { ... }

但假设我想通知预期响应类型,而不是任何object。我可以通过简单地替换来做到这一点object与所需的类型:

interface FetchOverload {
  (action: string, method: 'post' | 'get'): UserResponse;
  (action: string): UserResponse
}

const fetch: FetchOverload = (action: string, method: 'get' | 'post' = 'get'): UserResponse { ... }

如果我想更进一步,而不是说它只能返回类型的响应UserResponse,我可以返回一个泛型类型:

interface FetchOverload<T> {
  (action: string, method: 'post' | 'get'): T;
  (action: string): T
}

const fetch: FetchOverload<T> = (action: string, method: 'get' | 'post' = 'get'): T { ... }

问题是对于const没有通用类型T。事实上没有,我需要在某个地方声明T是一个通用类型,但我不知道在哪里!

我到处都尝试过,但无法让它理解有一种类型T:

<T> const fetch: ...
const <T> fetch: ...
const fetch <T>: ...
const fetch: <T> FetchOverload<T> = ...
const fetch: FetchOverload<T> = <T> (action: ...)

我找到的唯一解决方案是改变const通过重载将函数转换为本机函数:

function fetch<T>(action: string, method: 'post' | 'get'): T;
function fetch<T>(action: string): T;
function fetch<T>(action: string, method: 'post' | 'get' = 'get'): T { ... }

所以我想知道的是,实际上我是否需要这样使用它,或者是否还有一些解决方案可以继续使用const.


我“发现”了答案,因为我最终遇到了一个非常相似的问题这个问题 https://stackoverflow.com/questions/51197819/declaring-const-of-generic-type, 这个问题 https://stackoverflow.com/questions/32308370/what-is-the-syntax-for-typescript-arrow-functions-with-generics and in 这个答案 https://stackoverflow.com/a/59127985/755393 and 这个答案 https://stackoverflow.com/a/45576880/755393。基本上我只会这样做:

interface FetchOverload {
  <T> (action: string, method: 'post' | 'get'): T;
  <T> (action: string): T
}

export const fetch: FetchOverload = <T,> (action: string, method: 'get' | 'post' = 'get'): T { ... }

实际上,唯一奇怪的是类型后面的逗号,但它是强制性的,所以我没什么可做的。不过一切都已经解决了!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

const 函数、重载和泛型打字稿 的相关文章

随机推荐