jperasmus / stale-while-revalidate-cache

Storage-agnostic and configurable stale-while-revalidate cache helper for any function, for any JavaScript environment.
MIT License
62 stars 5 forks source link

Incorrect type when using async/await #26

Closed andreaspalsson closed 1 year ago

andreaspalsson commented 1 year ago

I ran into a type issue when using this package with async/await. If you provided an async function the value in the result object will be a promised and not the awaited value.

For example if you do this from the readme

const result = await swr(productId, async () => await fetchProductDetails(productId));

result.value will have the type Promise<Product> instead of Product

If you take example you will get a type error for the provided function

interface Product {
  id: string;
  name: string;
  description: string;
  price: number;
}

const result = await swr<Product>(productId, async () =>
  fetchProductDetails(productId) // Type error: Type 'Promise<Product>' is missing the following properties from type 'Product':
);

I have created a small repo that reproduce the issue https://github.com/andreaspalsson/stale-while-revalidate-cache-return-type

Looking at the code the function is always awaited and the awaited value is saved to the cache so this could be fixed by adding Awaited for FunctionReturnValue. Awaited was added in TypeScript 4.5.

I can create a PR with the suggested type updates.

jperasmus commented 1 year ago

Hi! Thanks for reporting it. I will gladly merge your PR to fix this.

jperasmus commented 1 year ago

Thanks for the fix. It is now available as v3.1.1

andreaspalsson commented 1 year ago

@jperasmus Thanks for the quick response and release.