react-promise-suspense
react-promise-suspense copied to clipboard
Make usePromise strongly-typed
trafficstars
Is it possible to make usePromise strongly typed?
Currently it's
function usePromise (
promise: (...inputs: any) => any,
inputs: Array<any>,
lifespan: number = 0
): any
Perhaps a strongly typed flavor could be provided, such as
function usePromise<T, A>(
promise: (A) => Promise<T>,
inputs: A,
lifespan: number = 0
): T
This might require some type coercion under the hood because the global singleton const promiseCaches: PromiseCache[] can't use type T above.
I would like to have this typed feature, because the current usePromise cannot catch type error like this:
function getApple(id: string): Promise<Apple> {...}
function useOrange(id: string): Orange {
return usePromise(getApple, [id]) // <-- It returns `any`, so type error cannot be caught
}
I'm not sure it it's necessary, but probably we need to use Parameters and ReturnType:
https://www.typescriptlang.org/docs/handbook/utility-types.html
You can use fork of this package that solves this issues and many others react-use-await