Type Safety Made Easy for Beginners: How to Effortlessly Achieve It with tRPC
HidetoshiYanagisawa
Posted on August 6, 2023
Table of Contents
- Introduction
- What Is tRPC?
- Strengths of Combining TypeScript and tRPC
- A Basic Use Case for tRPC
- Real Code Examples
- Conclusion
Introduction
Type safety in API development is a crucial aspect. By combining tRPC with TypeScript, even beginners can easily create type-safe APIs. This post will guide you through the basics of tRPC to real code examples.
What Is tRPC?
tRPC is a tool for sharing type information between the server and client. In this section, we’ll cover an overview and the benefits of tRPC.
Type Safety
It detects type errors at compile time, reducing runtime errors.
Strengths of Combining TypeScript and tRPC
Pairing TypeScript with tRPC makes it even more powerful. In this section, we’ll explore the reasons and advantages of this combination.
A Basic Use Case for tRPC
Here, we will explain a common use case of collecting visitor information on a website using tRPC as an example.
Real Code Examples
Server-Side Code
import { createTRPCRouter } from '@trpc/server';
const router = createTRPCRouter()
.query('getUser', {
resolve() {
return { id: 1, name: 'Bilbo' };
},
});
// Example of integration with Express
import express from 'express';
import { inferAsyncReturnType } from '@trpc/server';
import { z } from 'zod';
type Context = inferAsyncReturnType<typeof createContext>;
const createContext = async ({ req, res }: express.Request) => ({ req, res });
const app = express();
app.use('/trpc', trpcExpress.createExpressMiddleware({ router, createContext }));
Client-Side Code
import { createTRPCClient } from '@trpc/client';
const trpc = createTRPCClient({
url: '/trpc',
});
// Example of using the getUser query
const user = await trpc.query('getUser');
console.log(user.id, user.name); // 1, 'Bilbo'
Conclusion
tRPC is a powerful tool that even beginners can use to effortlessly achieve type-safe API development. Through this article, you’ve learned the basics of tRPC and understood how to apply it in real projects.
Feel free to try tRPC in your projects and experience its robust type safety features!
Posted on August 6, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
August 6, 2023