Skip to content

Typing issue with useAsync and TypeScript #256

Open
@samit4me

Description

@samit4me

Experiencing TypeScript errors when using useAsync version 10.0.0.

I feel like I'm probably doing something stupid, but I can replicate and seems like an issue.

Repo demonstrating the issue: https://github.com/samit4me/react-async-ts-issue


Given the data fetching method:

async function dataFetching(
  { id }: Props,
  { signal }: AbortController
): Promise<UserResponse> {
  const res = await fetch(`https://reqres.in/api/users/${id}`, { signal });
  if (!res.ok) throw new Error(res.statusText);
  const { data } = await res.json();
  return data;
}

When using useAsync via the shorthand method:

const { data, error, isPending } = useAsync(dataFetching, { id });

I get the following error:

Argument of type '({ id }: Props, { signal }: AbortController) => Promise<UserResponse>' is not assignable to parameter of type 'PromiseFn<UserResponse>'.
  Types of parameters '__0' and 'props' are incompatible.
    Property 'id' is missing in type 'AsyncProps<UserResponse>' but required in type 'Props'.ts(2345)

When using useAsync via the configuration object:

const { data, error, isPending } = useAsync({ promiseFn: dataFetching, id });

I get the following error:

No overload matches this call.
  Overload 1 of 2, '(options: AsyncOptions<UserResponse>): BaseAsyncState<UserResponse, AbstractState<UserResponse>>', gave the following error.
    Type '({ id }: Props, { signal }: AbortController) => Promise<UserResponse>' is not assignable to type 'PromiseFn<UserResponse>'.
      Types of parameters '__0' and 'props' are incompatible.
        Property 'id' is missing in type 'AsyncProps<UserResponse>' but required in type 'Props'.
  Overload 2 of 2, '(promiseFn: PromiseFn<any>, options?: AsyncOptions<any> | undefined): BaseAsyncState<any, AbstractState<any>>', gave the following error.
    Argument of type '{ promiseFn: ({ id }: Props, { signal }: AbortController) => Promise<UserResponse>; id: number; }' is not assignable to parameter of type 'PromiseFn<any>'.
      Object literal may only specify known properties, and 'promiseFn' does not exist in type 'PromiseFn<any>'.ts(2769)
User.tsx(5, 3): 'id' is declared here.
index.d.ts(82, 5): The expected type comes from property 'promiseFn' which is declared here on type 'AsyncOptions<UserResponse>'

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions