I have a generic CacheBuilder
factory witch takes a GetValue
function in argument and returns an instance of Cache
type GetValue<T> = (() => T) | (() => Promise<T>)
type CacheBuilder = <T> (getValue: GetValue<T>, options?: BuildCacheOptions<T>) => Cache<T>
One thing to note is the getValue
function can be both sync or async.
I'd like to be able to let Typescript infer T from getValue
, but to always return the Awaited
type.
Such as :
import { buildCache } from './cache'
// (buildCache is a CacheBuilder)
const getMyVal = () => Promise.resolve('foo')
// Inferred
const cache = buildCache(getMyVal)
My trouble is cache
is inferred as Cache<Promise<string>>
while I'd like it to be a Cache<string>
CodePudding user response:
Instead of storing the type T
in GetValue<T>
, we can store GetValue
directly like this, then get the return type of it and "await" it, but with types.
type CacheBuilder = <G extends GetValue<any>> (getValue: G, options?: BuildCacheOptions<Awaited<ReturnType<G>>>) => MyCache<Awaited<ReturnType<G>>>
CodePudding user response:
You can just use Awaited
on the return type for Cache
type GetValue<T> = (() => T)
type CacheBuilder = <T> (getValue: GetValue<T>, options?: BuildCacheOptions<T>) => Cache<Awaited<T>>