Issue
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>
Solution
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>>>
EDIT after accept:
Previous concept works perfectly, but here's a cleaner version, with extracted type as generic too (which allows the simple use of T
inside function implementation)
type CacheBuilder = <G extends GetValue<any>, T extends Awaited<ReturnType<G>>> (getValue: G, options?: BuildCacheOptions<T>) => MyCache<T>
Answered By - kelly
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.