I get a nested object as result of a GraphQL query with the query name as first-level key and the actual data on the second level:
{
getProduct: {
id: "1",
name: "test",
}
}
In my query function I automatically extract the first key of the object and return the value of getProduct
. However, I would like to infer the type of the first key as the return value of the query function.
type QueryReturn = FirstElement<GetProductQuery>; // should be { id: string; name: string }
All solutions I've found on the Internet infer the Head or Tail of an Array or Function.
I'm a bit late to the party but I saw that you were using graphql-codegen. I had a similar problem which I solved with:
type DataType = {
__typename?: string;
};
type FilteredQuery<T> = {
[P in keyof T as T[P] extends DataType ? P : never]: T[P];
};
type QueryData<T> = FilteredQuery<T>[keyof FilteredQuery<T>];
TypeScript playground example.