Typescript/Apollo: access property from in memory cache

Typescript/Apollo: access property from in memory cache



I'm using Apollo Client and am learning Typescript. I have a Mutation component with this update prop:


Mutation


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



I get two compilation errors:


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



I understand the general idea. readQuery might return null (which is it self confusing because the docs lead me to believe that an error is thrown when no results are found (https://www.apollographql.com/docs/react/advanced/caching.html#readquery).


readQuery


null



How can I get the compiler to let me read the property allTasks from the result of readQuery?


allTasks


readQuery



Also, FYI I tried running console.log(cache.readQuery( query: ALL_TASKS )) and confirmed that there is indeed valid data there with a property called.


console.log(cache.readQuery( query: ALL_TASKS ))




1 Answer
1



readQuery accepts a type argument for the type of the result; you can see this in the source code or by jumping to the declaration of readQuery in your IDE. Thus, you can do:


readQuery


readQuery


interface AllTasksResult
allTasks: any; // TODO: Put correct type here

// ...
const allTasks = cache.readQuery<AllTasksResult>( query: ALL_TASKS )!.allTasks;



About the null: Consider filing a bug for the inconsistency between the type declarations and the documentation. For now, the exclamation mark claims that you know the preceding expression (the return value of readQuery) won't be null or undefined.


null


readQuery






Thanks for the answer. I copy/pasted that into my code and am still getting Object is possibly 'null'.

– stoebelj
Sep 17 '18 at 11:08


Object is possibly 'null'.






Yes, I suppose you need to use a non-null assertion unless/until the type declarations are fixed. Updated the answer.

– Matt McCutchen
Sep 17 '18 at 15:26






This worked for me! Thanks Matt

– Ruffeng
Mar 5 at 10:06



Thanks for contributing an answer to Stack Overflow!



But avoid …



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Popular posts from this blog

.name

Greenpeace

Thomas Howard, 21st Earl of Arundel