'ApolloClient parse response field as object?

TLDR: How to make ApolloClient automatically parse responses such that a field within the response is deserialized to a particular object type? In particular, my response will have an _id field which will always be a bson ObjectID object.

Not sure how ask this or if I'm using to proper terminology so any help is appreciated. I have a graphql type like so:

type Post {
  _id: ID,
  ...
}

and a corresponding typescript interface like so:

import ObjectID from 'bson-objectid';

interface PostData {
  _id?: ObjectID,
  ...
}

I am sharing the typescript interface with both my backend and frontend, which has been very convenient not to have to redefine my types twice and keep them in sync, until now.

My problem is that when my client makes a query, like this (not exact but you get the idea, the returned data object will have some property that contains a list of PostData objects):

const { loading, data, error } = useQuery<PostData[], GetPostsArgs>(fetchQuery, { variables: fetchArgs });

when I access the field _id, it is not in fact already an ObjectID despite the fact that TS seems to think so (because of the type in the useQuery function, it is a string. So though VS Code will let me do something like data.someProp[0]._id.getTimestamp(), it crashes because it's a string and not a json ObjectID. Ideally, I'd like any of my responses that contain the _id field to be auto converted to ObjectIDs so that I don't have to do something like the following:

const ngDate = ObjectID(ngPost._id!.str).getTimestamp();


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source