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

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)