Typescript supports function overloading, which is pretty cool, and it's possible to make a constant function overloaded like this:
interface FetchOverload {
(action: string, method: 'post' | 'get'): object;
(action: string): object
}
const fetch: FetchOverload = (action: string, method: 'get' | 'post' = 'get'): object { ... }
But let's suppose I want to inform the type of response expected, instead of any object
. I can do this by simply replacing object
with the desired type:
interface FetchOverload {
(action: string, method: 'post' | 'get'): UserResponse;
(action: string): UserResponse
}
const fetch: FetchOverload = (action: string, method: 'get' | 'post' = 'get'): UserResponse { ... }
If I want to go even further and instead of saying it can only return a response of type UserResponse
, I could return a generic type:
interface FetchOverload<T> {
(action: string, method: 'post' | 'get'): T;
(action: string): T
}
const fetch: FetchOverload<T> = (action: string, method: 'get' | 'post' = 'get'): T { ... }
The problem is that for const
there is no a generic type T
. And in fact there isn't, I need to declare somewhere that T
is a generic type, but I don't know where!
I tried everywhere and couldn't make it understand that there is a type T
:
<T> const fetch: ...
const <T> fetch: ...
const fetch <T>: ...
const fetch: <T> FetchOverload<T> = ...
const fetch: FetchOverload<T> = <T> (action: ...)
The only solution I found was to transform the const
function into native functions with overload:
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 { ... }
So what I would like to know is if in fact I need to use it this way, or if there is still some solution to keep using const
.