Here is a snippet of TypeScript code I am working with:
type Chain = 'eth'
export type ApiMethods = {
getToken: {
path: 'tokens/'
(args: {
chain: Chain
tokenAddress: EthereumAddress
}): string
}
getRank: {
path: 'rank/wallets/'
(): string
}
}
type MethodParams<K extends keyof ApiMethods> = Parameters<ApiMethods[K]>[0]
type Api = {
[K in keyof ApiMethods]: MethodParams<K> extends undefined
? {path: ApiMethods[K]['path'], (): Promise<ReturnType<ApiMethods[K]>>}
: {path: ApiMethods[K]['path'], (args: MethodParams<K>): Promise<ReturnType<ApiMethods[K]>>}
}
type ApiParameters<K extends keyof Api> = Parameters<Api[K]>[0]
type ApiPath<K extends keyof Api, T = ApiParameters<K>> = T extends {chain: Chain}
? `${Api[K]['path']}${T['chain']}/`
: `${Api[K]['path']}`
type Payload<K extends keyof Api> = Omit<Parameters<Api[K]>[0], 'chain'>
export type ApiClientOptions = {
apiRoot?: string
}
class ApiClient {
private readonly options: Required<ApiClientOptions>
constructor(options: ApiClientOptions = {}) {
const defaultOptions = {
apiRoot: 'https://api.com/',
};
this.options = { ...defaultOptions, ...options };
}
private async callApi<K extends keyof Api>(path: ApiPath<K>, payload: Payload<K>): ReturnType<Api[K]> {
}
}
The Api
type encapsulates the function return type within a Promise
.
However, when invoking the callApi
function, an error occurs:
The return type of an async function or method must be the global Promise<T> type. Did you mean to write 'Promise<ReturnType<Api[K]>>'?
How can this error occur if the return type of the Api type is already wrapped in a Promise
? Any suggestions on how to resolve this issue?