DEV Community

HidetoshiYanagisawa
HidetoshiYanagisawa

Posted on

Type Safety Made Easy for Beginners: How to Effortlessly Achieve It with tRPC

Table of Contents

  1. Introduction
  2. What Is tRPC?
  3. Strengths of Combining TypeScript and tRPC
  4. A Basic Use Case for tRPC
  5. Real Code Examples
  6. 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 }));
Enter fullscreen mode Exit fullscreen mode

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'
Enter fullscreen mode Exit fullscreen mode

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!

Top comments (0)