使用 TS 模板文字建立強大的字串類型使用 TS 模板文字建立強大的字串類型

使用 TS 模板文字建立強大的字串類型

了解如何使用 TypeScript 範本文字類型動態組合字串文字類型,強制執行安全的 CSS 類別名稱和 API 端點。

簡介

TypeScript 提供了先進的類型系統,讓開發人員在編譯時對複雜的執行時間約束進行建模。

在這些功能中,模板文字類型(在 TypeScript 4.1 中引入)可讓您透過組合字串文字來定義結構化字串約束。

透過將 JavaScript 的模板文字語法 (```hello ${name}` ``) 套用到類型空間,您可以強制執行安全的 CSS 類別名稱模式、自動化 API 路由對應並建立類型化設計系統。本指南迴顧了範本文字類型的核心模式。


1. 模板文字類型的核心概念

模板文字類型的工作原理是採用聯合類型並將它們插入字串佔位符中。編譯器自動產生組合值的所有排列。

基本排列範例

type Align = "left" | "center" | "right";
type Valign = "top" | "middle" | "bottom";

// Define combinations of horizontal and vertical positions
// This automatically creates a union type containing 9 string variations:
// "left-top" | "left-middle" | ... | "right-bottom"
type Position = `${Align}-${Valign}`;

// Compiles successfully
const pos1: Position = "left-top";

// Error: "center-center" does not match the generated union type
const pos2: Position = "center-center";

從歷史上看,產生這些組合需要手動聲明每個變體。模板文字類型可讓您動態定義這些模式。


2. 實際生產用例

① 在設計系統中加入動態類別名稱前綴

建立 UI 庫時,您可以將元件屬性限制為有效的 BEM 樣式的 CSS 類別:

@@@代碼區塊1@@@

② 執行 API 主機協議

確保團隊成員使用正確的協定(例如“http”或“https”)和核准的網域名稱空間建立 API 端點:

type Protocol = "http" | "https";
type Domain = "api.example.com" | "staging.example.com";

// Enforce endpoints that begin with an approved protocol and domain
type ApiEndpoint = `${Protocol}://${Domain}/${string}`;

// Compiles successfully
const endpoint1: ApiEndpoint = "https://api.example.com/users";

// Error: Protocol "ftp" is not allowed
const endpoint2: ApiEndpoint = "ftp://api.example.com/users";

${string} 後綴允許任何尾隨 URL 路徑,同時驗證網域前綴。


3. 字串操作助手

TypeScript 提供內建實用程式類型來轉換範本文字類型內的字元:

  • Uppercase<S>:將字串轉換為大寫。
  • Lowercase<S>:將字串轉換為小寫。
  • Capitalize<S>:將字串的第一個字母大寫。
  • Uncapitalize<S>:取消字串的第一個字母的大寫。

您可以使用這些幫助程式來強制執行駝峰命名約定,例如資料物件上的 getter 和 setter 方法:

type UserFields = "name" | "email";

// Automatically generates method names: "getName" | "getEmail"
type GetterNames = `get${Capitalize<UserFields>}`;

const userGetters: Record<GetterNames, () => string> = {
  getName: () => "Takao",
  getEmail: () => "[email protected]"
};

結論

範本文字類型可讓您在應用程式中強制執行命名約定和字串結構。

  1. **組合佔位符內的多個並集以產生所有有效排列。 **
  2. **使用 ${string} 通配符強制執行前綴或後綴模式。 **
  3. **使用「Capitalize」等內建字串公用程式來自動執行駝峰命名法定義。 **

開始在類型空間中使用模板文字以在編譯時捕獲語法和命名錯誤。