Scalars & Enums in GraphQL
GraphQL includes primitive types called scalars, and enumerated types called enums. These types form the foundation of how GraphQL defines and validates the shape of data.
Scalars
Scalars represent the leaf values in a GraphQL query — the fields that resolve to concrete values.
Built-in Scalar Types
Scalar | Description |
---|---|
Int |
A 32-bit signed integer |
Float |
A double-precision floating-point value |
String |
A UTF-8 character sequence |
Boolean |
A true or false value |
ID |
A unique identifier (often a string) |
Example
Custom Scalars
You can define custom scalars for domain-specific values like Date
, URL
, Email
, or JSON
.
Schema Definition
Server-Side Handling (Example in Apollo Server)
const { GraphQLScalarType } = require('graphql');
const DateScalar = new GraphQLScalarType({
name: 'Date',
serialize(value) {
return value.toISOString();
},
parseValue(value) {
return new Date(value);
},
parseLiteral(ast) {
return new Date(ast.value);
},
});
Custom scalars require implementation of how they’re serialized and parsed.
Enums
Enums represent a fixed set of values. They make your schema more expressive and self-documenting.
In this example, the role
field can only be one of ADMIN
, USER
, or GUEST
.
Enums in Input Types
Enums are especially useful in input arguments or filters.
Best Practices
- ✅ Use enums to restrict valid values (instead of free-form strings)
- ✅ Validate custom scalars properly to avoid invalid data
- ✅ Favor scalars for basic values, and use custom ones carefully
- ✅ Document your enums well for clarity
Tools
- graphql-scalars — A library of common custom scalars
- GraphQL Code Generator — Supports scalars mapping in TypeScript and more
- Apollo Docs – Scalars & Enums
Summary
- Scalars represent primitive leaf values.
- Enums define a set of constant values.
- Both are crucial for type safety, validation, and schema clarity.