0Pricing
tRPC End-to-End Type Safe APIs · 课时

代码共享与复用

学习最大化客户端与服务器之间代码复用的策略,尤其适用于类型和工具。

代码共享与复用 是 CoddyKit 上的免费 tRPC End-to-End Type Safe APIs 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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.

常见问题解答

「代码共享与复用」课时是免费的吗?

是的 — 「代码共享与复用」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 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,全天候 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