我在用阿波罗客户端,正在学习打字。我有一个 Mutation
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
readQuery
null
allTasks 由于 ?
allTasks
另外,我试过跑步 console.log(cache.readQuery({ query: ALL_TASKS }))
console.log(cache.readQuery({ query: ALL_TASKS }))
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或未定义。