[英]const functions, overloads and generics typescript
Typescript 支持 function 重载,这很酷,并且可以像这样使常量 function 重载:
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 { ... }
如果我想进一步 go 而不是说它只能返回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 转换为具有重载的本机函数:
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
。
我“发现”了答案,因为我最终在这个问题、 这个问题、这个答案和这个答案中遇到了一个非常相似的问题。 基本上我会这样做:
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 { ... }
实际上,唯一奇怪的是类型后面的逗号,但它是强制性的,所以我没有太多事情要做。 但是一切都解决了!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.