TypeScript 品牌類型:防止原始混亂TypeScript 品牌類型:防止原始混亂

TypeScript 品牌類型:防止原始混亂

深入研究用於名目打字模擬的 TypeScript 品牌類型:品牌模式、交叉類型、驗證函數以及 ID、貨幣和電子郵件的用例。

TypeScript 使用結構類型(鴨子類型):具有相同形狀的兩種類型可以互換。當基元類型傳回域概念時,這會導致錯誤 - 在需要“orderId”的地方傳遞“userId”,兩者都鍵入為“string”。考慮一個發送電子郵件但意外收到資料庫 ID 而不是地址的函數,因為兩者都是「字串」。品牌類型透過添加幻像類型標記來解決這個問題,該標記在編譯時以零運行時成本區分結構相同的類型。

品牌模式

核心技術使用具有幻影品牌屬性的交叉類型:

type Brand<T, B> = T & { __brand: B };

type UserId = Brand<string, "UserId">;
type OrderId = Brand<string, "OrderId">;
type Email = Brand<string, "Email">;

__brand 屬性在執行時永遠不存在-它在編譯期間會被刪除。 TypeScript 將「UserId」和「OrderId」視為不同的類型,因為它們的品牌不同。

@@@代碼區塊1@@@

使用“declare”或將品牌屬性設定為可選以避免運行時分配問題:

// Better: unique symbol brand prevents accidental casting
declare const UserIdBrand: unique symbol;
type UserId = string & { [UserIdBrand]: true };

declare const OrderIdBrand: unique symbol;
type OrderId = string & { [OrderIdBrand]: true };

類型保護和驗證函數

由於品牌在運行時不存在,因此必須在系統邊界(API 端點、資料庫結果和表單提交)對值進行驗證和品牌化。

// Factory function with validation
function createUserId(value: string): UserId {
  if (!/^user_[a-f0-9]{24}$/.test(value)) {
    throw new Error(`Invalid UserId format: ${value}`);
  }
  return value as UserId;
}

// Type guard
function isUserId(value: string): value is UserId {
  return /^user_[a-f0-9]{24}$/.test(value);
}

// Assertion function
function assertUserId(value: string): asserts value is UserId {
  if (!isUserId(value)) {
    throw new Error(`Expected a valid UserId, got: ${value}`);
  }
}

為複雜型別編寫驗證器並處理反序列化:

interface User {
  id: UserId;
  email: Email;
  name: string;
}

function parseUser(data: unknown): User {
  const raw = data as Record<string, unknown>;
  return {
    id: createUserId(String(raw.id)),
    email: createEmail(String(raw.email)),
    name: String(raw.name),
  };
}

域原語的用例

品牌類型在原始混亂造成真正損害的領域中大放異彩。

網域品牌類型預防
電子商務用戶 ID、訂單 ID、產品 ID交叉 ID 分配錯誤
金融科技美元、日圓、歐元貨幣算術錯誤
醫療保健PatientId、ProviderId、ClaimId患者之間的資料外洩
SaaSApiKey、SessionToken憑證濫用

貨幣處理就是一個引人注目的例子:

type USD = Brand<number, "USD">;
type JPY = Brand<number, "JPY">;

function addUSD(a: USD, b: USD): USD {
  return (a + b) as USD;
}

function addJPY(a: JPY, b: JPY): JPY {
  return (a + b) as JPY;
}

const price: USD = 29.99 as USD;
const tax: USD = 3.00 as USD;
const yenAmount: JPY = 5000 as JPY;

addUSD(price, tax);       // OK
addUSD(price, yenAmount); // Type error: 'JPY' not assignable to 'USD'

通用品牌類型和函式庫

為常見品牌模式建立通用實用程式:

type Entity<T extends string> = Brand<string, T>;

interface Repository<T, TId extends string> {
  findById(id: Entity<TId>): Promise<T>;
  save(entity: T): Promise<void>;
}

// Usage with Zod for runtime validation + branding
import { z } from "zod";

const UserIdSchema = z.string().brand("UserId");
type UserId = z.infer<typeof UserIdSchema>;

const userRepo: Repository<User, "UserId"> = {
  async findById(id) {
    // Type-safe database query
    return db.query("SELECT * FROM users WHERE id = $1", [id]);
  },
  async save(user) { /* ... */ },
};
圖書館品牌推廣方法運行時成本
類型盛宴不透明<T,令牌>零
io-ts品牌編解碼器僅驗證
佐德.brand() 方法僅驗證
手冊交叉口類型零

效能和遷移

品牌類型的運行時開銷為零——品牌屬性在編譯期間被刪除。驗證函數確實會增加運行時成本,因此在系統邊界驗證一次並透過內部程式碼庫傳播品牌類型。

// Validate at boundary, propagate internally
async function handleRequest(rawId: string) {
  const userId = createUserId(rawId); // Validate once
  const user = await userRepo.findById(userId);
  await sendEmail(user.email, welcomeMessage);
  // userId and user.email are branded — type-safe throughout
}

增量遷移:從最關鍵的域原語(ID、貨幣金額)開始,在模組邊界中新增品牌類型,並使用 lint 規則強制執行。從新程式碼開始或一次重構一個模組,而不是一攬子遷移。

品牌類型提供零成本的編譯時安全性,透過類型傳達域含義來提高程式碼可讀性,並防止整個類別的錯誤。安全方面的好處遠遠超過了冗長的代價。將它們整合到您的系統邊界,並讓類型檢查器保護您的網域邏輯。