Template Literal 类型
一句话解释
template literal 类型 uses template literal 语法 at 类型 level 到创建字符串类型那个 match 特定模式.
用大白话说
Template literal 类型 bring template literal 语法到 类型 level. type Greeting = Hello ${字符串}`` matches any string starting with "Hello ". This lets you constrain strings to specific patterns.
They are useful for defining event names, CSS property values, URL patterns, and other structured strings. Combined with union types and mapped types, they can create very precise string types.
For example, 类型 HttpMethod = $${"GET" | "POST" | "PUT"} /api/${string}`` matches strings like "GET /API/用户" or "POST /API/posts".
示例
typescript
type EventName = `on${Capitalize<string>}`;
type T = EventName; // matches "onClick", "onLoad", etc.
const handler: EventName = "onClick"; // OKtemplate literal 类型 constrains 字符串到 开始使用 'on' followed 通过 capitalized word.
相关术语
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。