Query Result Not Assignable to Custom Type Error
If you get a type error similar to the following when you pass the result of query.graph or useQueryGraphStep to a function or variable that uses your own type:
Why this Error Occurred#
Medusa generates the types of Query results from the schema of your modules and their links. In these generated types, a to-many relation of a module link, such as an order's payment_collections, has the following type:
Maybe<T> is a shorthand for T | null. So, TypeScript considers both the array and each of its items nullable.
If you define your own type for the retrieved data where the relation is a non-nullable array, TypeScript can't assign the Query result to it. For example:
1type OrderSummary = {2 id: string3 payment_collections: {4 id: string5 amount: number6 }[]7}8 9function summarizeOrder(order: OrderSummary) {10 // ...11}12 13const { data: orders } = await query.graph({14 entity: "order",15 fields: [16 "id",17 "payment_collections.id",18 "payment_collections.amount",19 ],20})21 22// TS2345 error23summarizeOrder(orders[0])
This error only affects type-checking. Your code works as expected at runtime, but the type error fails the build command.
How to Fix it#
Option 1: Remove Null Items from the Relation#
Map the Query result to your type, and filter out null items from the relation's array with a type predicate. In a workflow, perform the mapping in a transform function.
For example:
The type predicate pc is NonNullable<typeof pc> tells TypeScript that the filtered array no longer has null items, so the result matches your type.
Option 2: Accept Nullable Values in Your Type#
Alternatively, change your type to accept null for the relation and its items:
Then, handle the null values in the code that uses the type. For example: