react-promise-suspense icon indicating copy to clipboard operation
react-promise-suspense copied to clipboard

Make usePromise strongly-typed

Open ryanberckmans opened this issue 5 years ago • 2 comments
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.

ryanberckmans avatar Jun 17 '20 21:06 ryanberckmans

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

ngocdaothanh avatar Feb 06 '21 22:02 ngocdaothanh

You can use fork of this package that solves this issues and many others react-use-await

msereniti avatar Jan 20 '22 11:01 msereniti