typescriptgraphqldataloader

Type error initializing DataLoader with Typescript


I'm trying to initialize an instance of DataLoader using the following code:

const authorLoader = new DataLoader(async (keys:string[]) => {
    // Return an author for each book
});

I'm getting the following error:

Argument of type '(keys: string[]) => Promise<Author[]>' is not assignable to parameter of type 'BatchLoadFn<string, Author>'.
Types of parameters 'keys' and 'keys' are incompatible.
The type 'readonly string[]' is 'readonly' and cannot be assigned to the mutable type 'string[]'

Why am I getting this error and how do I fix it? I read up on Generics and the source code for dataloader but haven't found a solution.

Note: keys is of type string[] and not number[] because I'm using uuid's.


Solution

  • Like the error message says, DataLoader is expecting a readonly string[] as the function argument, but you have annotated it as string[].

    const authorLoader = new DataLoader(async (keys: readonly string[]) => {
        // Return an author for each book
    });