How to Fix 'Expected Type but Got' Error in GraphQL
Why This Happens
This error occurs because GraphQL expects a specific type for a field or argument, but the query or mutation provides a different type. This mismatch can be due to wrong data types, missing required fields, or incorrect list formats.
type Query { getUser(id: ID!): User } type User { id: ID! name: String! } # Query with wrong type for id (should be ID, given as Int) { getUser(id: 123) { id name } }
The Fix
Change the input to match the expected type exactly. For example, if the schema expects an ID! type, provide a string value or quoted ID. Also, ensure lists and nullability match the schema.
type Query { getUser(id: ID!): User } type User { id: ID! name: String! } # Correct query with id as a string { getUser(id: "123") { id name } }
Prevention
To avoid this error, always check your schema types before writing queries or mutations. Use GraphQL tools like IDE plugins or linters that validate your queries against the schema. Also, be mindful of required fields and list formats.
Related Errors
Similar errors include Cannot query field when a field does not exist, or Variable "$var" got invalid value when variables have wrong types. Fix these by matching schema definitions and using correct variable types.