I'm facing a challenge in TypeScript.
Essentially, I am attempting to replicate the functionality of useSWR. In useSWR, you can pass an array of arguments as the first parameter in a function, and then provide a callback function as the second parameter where the elements of the array become the arguments for the callback.
For instance:
const fetcher = async(arg1: string, arg2: string): Promise<string | boolean> => {
try {
return arg1 + ' - ' + arg2
} catch(e) {
return false
}
}
type Fetcher<T, A extends any[]> = (...args: A) => Promise<T>
const useAdminEndpoint = <T, A extends any[]>(key: A, fetcher: Fetcher<T, A>) => {
const run = async() => {
try {
return await fetcher.apply(null,key)
} catch(e) {
return false
}
}
return result
}
const result = useAdminEndpoint(['hello',2],(h,g) => fetcher(h,g))
The parameter types represent the types of the items within the array as a tuple, rather than mapping them to specific variables like arg0 = array[0], arg1 = array[1], and so on.
I'm unsure about the terminology for what I'm attempting to achieve here, making it difficult to search for solutions. Is it feasible to have the order of arguments infer their respective type from the items in the array?