使用 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”等内置字符串实用程序来自动执行驼峰命名法定义。

开始在类型空间中使用模板文字以在编译时捕获语法和命名错误。