I have a tricky Typescript problem I can't seem to solve. I would like to infer values based on a generic. However, the catch is the inferred types needs to come from an imported file.
To explain in an example, this is my generic function.
import { DocumentNode, print } from "graphql"
type GraphqlRequest = <Query, Variables = {}>({ query, variables }: { query: DocumentNode, variables?: Variables }) => Promise<Query>
const fetchQuery: GraphqlRequest = async ({ query, variables = {} }) => {
return database(JSON.stringify({ query: print(query), variables }))
}
And I use it in the following way:
import { UserBlogItems, UserBlogItemsQuery, UserBlogItemsQueryVariables } from "~/graphql"
fetchQuery<UserBlogItemsQuery, UserBlogItemsQueryVariables>({ query: UserBlogItems, variables: { user } })
Which works great because I can get the correct types checking on the variables and the query response.
What I would like to be able to do is just include the DocumentNode
and have Typescript look up the Query
and Variables
from the "~/graphql` file. This way I can have the function look a lot cleaner.
import { UserBlogItems } from "~/graphql"
fetchQuery({ query: UserBlogItems, variables: { user }})
I can ensure 100% always that in the ~/graphql
file the format will be:
DocumentNode: [myquery]
(egUserBlogItems
)Query: [myquery]Query
(egUserBlogItemsQuery
)Variables: [myquery]QueryVariables
(egUserBlogItemsQueryVariables
)
Is this possible in Typescript?