0Pricing
tRPC End-to-End Type Safe APIs · レッスン

コード共有と再利用性

特に型やユーティリティを中心に、クライアントとサーバー間でコードを最大限再利用するための戦略を学びます。

「コード共有と再利用性」はCoddyKit上の無料tRPC End-to-End Type Safe APIsレッスンです。 これはレッスン2/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはtRPC End-to-End Type Safe APIs学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 tRPC End-to-End Type Safe APIsコースには全4レッスンが含まれています。

このレッスンの一部はまだ翻訳されておらず、英語で表示されています。

Why Share Code?

In a tRPC monorepo, you often have multiple applications (client, server, admin panel) that need to interact with the same data structures or perform similar tasks.

Code sharing is a powerful technique that helps reduce duplication, ensure consistency, and improve the overall maintainability of your project.

Types Across Client & Server

One of tRPC's biggest advantages is end-to-end type safety. This means your frontend automatically knows the types of data your backend sends and receives.

This magic relies heavily on sharing TypeScript types and interfaces between your client and server applications.

Defining a Shared Type

Let's create a simple User interface in a dedicated packages/types directory. This package will be imported by both your server and client.

/* packages/types/src/user.ts */
export interface User {
  id: string;
  name: string;
  email: string;
}

Server-side Shared Types

Now, we can use this User type to define the expected output of a tRPC query on our backend. This ensures the data sent from the server strictly adheres to the User structure.

/* packages/server/src/router/user.ts */
import { publicProcedure, router } from '../trpc';
import { User } from '@my-monorepo/types'; // Import shared type

export const userRouter = router({
  getUsers: publicProcedure
    .query(async () => {
      const users: User[] = [
        { id: '1', name: 'Alice', email: 'alice@example.com' },
        { id: '2', name: 'Bob', email: 'bob@example.com' },
      ];
      return users; // tRPC infers return type as User[]
    }),
});

Client-side Shared Types

On the client, tRPC automatically infers the types for users based on the server's definition. While explicit import isn't always needed for inference, it improves clarity and allows you to use the type for local client-side state or props.

/* packages/client/src/components/UserList.tsx */
import { trpc } from '../utils/trpc';
import { User } from '@my-monorepo/types'; // Optional, but good practice

function UserList() {
  const { data: users, isLoading } = trpc.user.getUsers.useQuery();

  if (isLoading) return <div>Loading users...</div>;

  return (
    <div>
      {users?.map((user: User) => ( // 'user' is typed as User
        <p key={user.id}>{user.name} ({user.email})</p>
      ))}
    </div>
  );
}

Sharing Utility Functions

Beyond types, many other pieces of code can be shared. This includes common utility functions, constants, validation schemas (like Zod schemas), or even shared UI components if you're using a component library.

Sharing these helps maintain a consistent user experience and reduces redundant code across your applications.

Creating a Utility Package

Let's create a simple utility function in a packages/utils directory that formats a full name. We'll also include a shared constant.

/* packages/utils/src/format.ts */
export function formatFullName(firstName: string, lastName: string): string {
  return `${firstName} ${lastName}`;
}

export const APP_NAME = 'CoddyKit Learn'; // Example constant

Server-side Utilities

You can import and use these shared utility functions directly in your tRPC backend procedures. This ensures consistent logic, regardless of whether it's triggered by an API call or internal server processes.

/* packages/server/src/router/profile.ts */
import { publicProcedure, router } from '../trpc';
import { formatFullName } from '@my-monorepo/utils'; // Import shared utility
import { z } from 'zod'; // Assuming Zod is configured

export const profileRouter = router({
  getUserProfile: publicProcedure
    .input(z.object({ firstName: z.string(), lastName: z.string() }))
    .query(({ input }) => {
      const fullName = formatFullName(input.firstName, input.lastName);
      return { greeting: `Hello, ${fullName}!` };
    }),
});

Client-side Utilities

Similarly, your client-side application can import and use the exact same utility functions and constants. This guarantees that calculations or displayed text are consistent with the server's logic.

/* packages/client/src/components/Greeting.tsx */
import { formatFullName, APP_NAME } from '@my-monorepo/utils'; // Import shared utility

function Greeting() {
  const firstName = "Jane";
  const lastName = "Doe";
  const formattedName = formatFullName(firstName, lastName);

  return (
    <div>
      <h1>Welcome to {APP_NAME}!</h1>
      <p>User: {formattedName}</p>
    </div>
  );
}

Best Practices for Shared Code

  • Granularity: Create small, focused shared packages (e.g., types, utils, ui).
  • Dependencies: Shared packages should have minimal external dependencies to avoid bloating other apps.
  • Avoid Circular Deps: Be careful not to create circular dependencies between shared packages or between app and shared packages.
  • Testing: Test shared code thoroughly, as changes can affect multiple applications.

Shared Code Benefits

Which of the following are primary benefits of sharing types and utility functions between client and server in a tRPC monorepo?

Recap: Sharing is Caring!

We explored how sharing types and utility functions in a tRPC monorepo is key to maximizing efficiency. This approach reduces duplication, enhances type safety, and improves overall maintainability across your client and server applications. By structuring your project carefully, you can build robust and consistent full-stack applications.

よくある質問

「コード共有と再利用性」レッスンは無料ですか?

はい。「コード共有と再利用性」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、tRPC End-to-End Type Safe APIsコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 tRPC End-to-End Type Safe APIsコースには全4レッスンが含まれています。

「コード共有と再利用性」で何を学びますか?

特に型やユーティリティを中心に、クライアントとサーバー間でコードを最大限再利用するための戦略を学びます。 ブラウザで直接実行するハンズオンコードでtRPC End-to-End Type Safe APIsを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

tRPC End-to-End Type Safe APIsを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのtRPC End-to-End Type Safe APIsは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン2/4です。

「コード共有と再利用性」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このtRPC End-to-End Type Safe APIsレッスンでコードを書いて実行できますか?

はい。すべてのtRPC End-to-End Type Safe APIsレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. tRPCモノレポの設定
  2. コード共有と再利用性
  3. tRPC機能の拡張
  4. 共有tRPCパッケージのバージョン管理と公開
← tRPC End-to-End Type Safe APIsに戻る