模板字符串字面量类型 (template literal types) 允许你通过将其他类型插值到模板中来构建新的字符串字面量类型 — 在 type 层面进行字符串操作。
ts
type Greeting = `Hello, ${string}`;
const a: Greeting = "Hello, world"; // ✅
: = ;
模板字符串字面量类型 (template literal types) 允许你通过将其他类型插值到模板中来构建新的字符串字面量类型 — 在 type 层面进行字符串操作。
type Greeting = `Hello, ${string}`;
const a: Greeting = "Hello, world"; // ✅
: = ;
type Color = "red" | "blue";
type Shade = "light" | "dark";
type Variant = `${Shade}-${Color}`;
// "light-red" | "light-blue" | "dark-red" | "dark-blue" — all combinations
编译器会展开 unions 的每个组合 — 这对于自动生成有效的字符串键(CSS 类、事件名称、路由模式)很有用。
type Entity = "user" | "post";
type Event = `${Entity}:${"created" | "deleted"}`;
// "user:created" | "user:deleted" | "post:created" | "post:deleted"
function on(event: Event, cb: () => void) {}
on("user:created", () => {}); // ✅
on("user:updated", () => {}); // ❌ not a valid event
type Getters<T> = {
[K in keyof T & string as `get${Capitalize<K>}`]: () => T[K];
};
// { name: string } → { getName: () => string }
Uppercase、Lowercase、Capitalize、Uncapitalize 是内置的内在辅助类型。
模板字符串字面量类型使基于字符串的 API 变得类型安全:路由参数、事件系统、CSS-in-JS、ORM 列名。
相比接受任何 string,你可以限制到精确的、生成的有效字符串集合 — 在曾经是字符串类型的地方在编译时捕捉拼写错误。