【问题标题】:Type error initializing DataLoader with Typescript使用 Typescript 初始化 DataLoader 时出现类型错误
【发布时间】:2020-09-15 00:28:45
【问题描述】:

我正在尝试使用以下代码初始化 DataLoader 的实例:

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

我收到以下错误:

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[]'

为什么会出现此错误,我该如何解决?我阅读了Generics 和 dataloader 的源代码,但没有找到解决方案。

注意:keys 的类型是 string[],而不是 number[],因为我使用的是 uuid

【问题讨论】:

    标签: typescript graphql dataloader


    【解决方案1】:

    如错误消息所述,DataLoader 期望 readonly string[] 作为函数参数,但您已将其注释为 string[]

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

    【讨论】:

    • 哇,我很尴尬地看到解决方案如此简单!谢谢。
    • 我们都去过!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-13
    • 1970-01-01
    • 1970-01-01
    • 2018-02-06
    • 2021-05-08
    • 2021-09-22
    • 1970-01-01
    相关资源
    最近更新 更多