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
.