代码之家  ›  专栏  ›  技术社区  ›  stoebelj

Typescript/Apollo:从内存缓存访问属性

  •  1
  • stoebelj  · 技术社区  · 7 年前

    我在用阿波罗客户端,正在学习打字。我有一个 Mutation

    (cache, { data: { createTask } }) => {
        const allTasks = cache.readQuery({ query: ALL_TASKS }).allTasks;
    }
    

    我有两个编译错误:

    Object is possibly 'null'.
    Property 'allTasks' does not exist on type '{}'.
    

    readQuery 可能会回来 null (这是自相矛盾的,因为文档让我相信,当找不到结果时会抛出错误( https://www.apollographql.com/docs/react/advanced/caching.html#readquery

    allTasks 由于 ?

    另外,我试过跑步 console.log(cache.readQuery({ query: ALL_TASKS }))

    1 回复  |  直到 7 年前
        1
  •  13
  •   Matt McCutchen    7 年前

    readQuery 接受结果类型的类型参数;您可以看到 in the source code 或者跳到 读取查询 在IDE中。因此,您可以:

    interface AllTasksResult {
      allTasks: any;  // TODO: Put correct type here
    }
    // ...
    const allTasks = cache.readQuery<AllTasksResult>({ query: ALL_TASKS })!.allTasks;
    

    关于 null :考虑为类型声明和文档之间的不一致性提交一个bug。现在,感叹号声明您知道前面的表达式(的返回值) )不会为null或未定义。

    推荐文章