GraphQL in TypeScript: Complete Overview of Libraries and Tools
GraphQL and TypeScript are an ideal combination for building modern APIs. TypeScript adds static typing, which perfectly complements GraphQL's strict type system. In this article, we will cover the main libraries and tools for working with GraphQL in TypeScript, including installation, code examples, and best practices.
Why TypeScript for GraphQL?
GraphQL queries and responses have a strict structure, and TypeScript allows you to validate this structure at compile time. This eliminates a whole class of errors related to incorrect data types. Key benefits:
- Type safety — automatic type generation from the GraphQL schema
- Autocompletion — IDE suggests query fields and types
- Refactoring — schema changes automatically update all client queries
- Error minimization — type errors are detected before code execution
Main Libraries for the Server Side
1. TypeGraphQL
TypeGraphQL is the most popular library for building GraphQL APIs in TypeScript. It uses decorators to define the schema and resolvers.
Installation:
npm install type-graphql graphql reflect-metadataExample of type and resolver declaration:
import { ObjectType, Field, Int, Resolver, Query, Arg } from "type-graphql";
@ObjectType()class User { @Field(() => Int) id: number;
@Field() name: string;
@Field({ nullable: true }) email?: string;}
@Resolver(User)class UserResolver { @Query(() => User, { nullable: true }) async user(@Arg("id", () => Int) id: number): Promise<User | null> { // Logic to fetch user from DB return { id, name: "John", email: "john@example.com" }; }}Schema building:
import { buildSchema } from "type-graphql";
const schema = await buildSchema({ resolvers: [UserResolver], emitSchemaFile: true,});2. GraphQL Yoga
GraphQL Yoga is a universal GraphQL server that works great with TypeScript. It is based on Express but supports any platform.
Installation:
npm install graphql-yoga graphqlServer example:
import { createYoga, createSchema } from "graphql-yoga";import { createServer } from "node:http";
const schema = createSchema({ typeDefs: ` type Query { hello: String user(id: Int!): User } type User { id: Int! name: String } `, resolvers: { Query: { hello: () => "Hello, GraphQL!", user: (_, { id }) => ({ id, name: "Alice" }), }, },});
const yoga = createYoga({ schema });const server = createServer(yoga);server.listen(4000, () => console.log("Server running on http://localhost:4000/graphql"));Libraries for the Client Side
3. Apollo Client (with TypeScript support)
Apollo Client is a powerful client for working with GraphQL. With TypeScript, it provides full query typing.
Installation:
npm install @apollo/client graphqlExample of a typed query:
import { gql, useQuery } from "@apollo/client";
const GET_USER = gql` query GetUser($id: Int!) { user(id: $id) { id name email } }`;
interface UserData { user: { id: number; name: string; email?: string; };}
function UserProfile({ userId }: { userId: number }) { const { loading, data } = useQuery<UserData>(GET_USER, { variables: { id: userId }, });
if (loading) return <p>Loading...</p>; return <p>{data?.user.name}</p>;}