4

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.

Dan
  • 641
  • 1
  • 7
  • 17

2 Answers2

6

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
});
TLadd
  • 6,488
  • 2
  • 32
  • 40
0

Check the @InBatches lib, it makes it easier to implement dataloader using a decorator.

import { InBatches } from 'inbatches';

class MyService {

  // (optional) overloaded method, where you define the keys as `number` and the return type as `string` for typings
  async fetch(keys: number): Promise<string>;

  // in reality the Decorator will wrap this method and it will never be called with a single key :)
  @InBatches() // This method is now batch-enabled
  async fetch(keys: number | number[]): Promise<string | string[]> {
    if (Array.isArray(keys)) {
      return this.db.getMany(keys);
    }

    // the Decorator will wrap this method and because of that it will never be called with a single key
    throw new Error('It will never be called with a single key ');
  }
}

https://www.npmjs.com/package/inbatches