I have a question regarding TypeScript version 4.1.5.
Let's consider the scenario where I am making a GraphQL query in a function called getItems
. The result, items
, inherits an unnamed generated type from this function. Now, I need to perform a map operation on these items, but I am unsure how to specify the type for each element when I do so.
const items = getItems(); // calling a GraphQL query
const transformedItems = items.map((item: any) => {
return {
// transformation logic goes here
};
});
When I hover over items
in VSCode, it shows that it is an array of an unnamed generated type, containing the attributes and connectors I requested in the GraphQL query in getItems
:
const items: ({
__typename?: "myItem" | undefined;
} & Pick<myItem, "id" | "createdAt" | "updatedAt" | "apiId" | "lastUpdated" | "balanceAfterThis" | ... 23 more ... | "apiCreatedAt">)[]
Currently, I have used the any
type as I couldn't import the generated type for usage here. This approach of using any
type can lead to errors being overlooked which could have been caught by specifying the correct type. I am looking for a way to use the correct type but I am unsure of how to proceed.
(I prefer not to rewrite the map operation as a loop just to avoid the type issue.)
(I also do not want to manually define this generated type, since the GraphQL function may change in the future requiring changes to my manual type definition as well.)
Is there a way to dynamically retrieve the type stored in items
and apply it in the map operation? Alternatively, is there another solution to address this type problem? Your insights and suggestions would be greatly appreciated. Thank you for your attention.