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.
2 Answers
Reset to default
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
});
2
-
2
wow, I'm embarrassed to see the solution was so simple! thank you.
– DanMay 27, 2020 at 20:22
-
1
We've all been there!
– TLaddMay 27, 2020 at 21:52
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 😉');
}
}
Not the answer you're looking for? Browse other questions tagged
or ask your own question.
or ask your own question.
|