0
0
GraphqlHow-ToBeginner · 3 min read

How to Extend Type in GraphQL: Syntax and Examples

In GraphQL, you can extend an existing type using the extend type keyword followed by the type name and new fields. This allows you to add fields to a type without modifying the original type definition directly.
📐

Syntax

The extend type keyword is used to add new fields to an existing type. You write extend type TypeName { ... } where TypeName is the name of the type you want to extend. Inside the braces, you list the new fields you want to add.

This helps keep your schema modular and organized, especially when splitting schema definitions across files.

graphql
extend type TypeName {
  newField: FieldType
}
💻

Example

This example shows how to extend a User type by adding a new field age without changing the original User type definition.

graphql
type User {
  id: ID!
  name: String!
}

extend type User {
  age: Int
}
Output
Querying <code>User</code> now supports <code>id</code>, <code>name</code>, and <code>age</code> fields.
⚠️

Common Pitfalls

One common mistake is trying to redefine a field that already exists in the original type, which causes errors. Also, extend only works with object types, not scalar or enum types.

Another pitfall is forgetting to merge the extended type into your schema if you split schema files.

graphql
type User {
  id: ID!
  name: String!
}

# Wrong: redefining existing field 'name'
extend type User {
  name: String
  age: Int
}

# Correct: only add new fields
extend type User {
  age: Int
}
📊

Quick Reference

KeywordPurposeExample
extend typeAdd fields to existing object typeextend type User { age: Int }
typeDefine a new object typetype User { id: ID! name: String! }
fieldA property inside a typeage: Int

Key Takeaways

Use extend type TypeName to add new fields to an existing GraphQL type.
Do not redefine existing fields when extending a type to avoid errors.
Extending types helps keep your schema modular and easier to maintain.
Remember to merge all schema parts if your schema is split across files.