TypeScript 模板字面量
在类型层组合事件、方法路径和CSS类名,明确格式检查不会生成或清洗运行时字符串。
学完这一章,你能够
- 操作四种内置大小写工具
- 让路径示例与模板真正匹配
- 识别联合组合数量和number模板边界
模板类型不执行模板表达式
typescript
type World="world";type Greeting=`Hello ${World}`;
const greeting:Greeting="Hello world";
类型层模板用字符串字面量和允许的插值类型构建约束;运行时的`${value}`模板表达式则实际创建字符串。不能在console.log中把Greeting等类型名当值使用,也不能认为类型会替输入自动补前缀。
四个大小写工具用值约束核对
typescript
const upper:Uppercase<"hello">="HELLO";
const lower:Lowercase<"HELLO">="hello";
const capital:Capitalize<"hello">="Hello";
const uncapital:Uncapitalize<"Hello">="hello";
这些是类型运算,不会把一个运行时变量自动转成大小写。要改变实际文字,调用相应字符串函数;大小写规则也不能等同完整的区域语言文字校验。
事件名和处理器名
typescript
type EventName=`on${Capitalize<string>}`;
type Handler=`handle${Capitalize<string>}`;
const click:EventName="onClick";const focus:EventName="onFocus";
const handler:Handler="handleSubmit";
它限制一定格式,不自动验证事件真实存在。需要有限集合时用"click"|"focus"再插值,能减少拼错名称被宽泛后缀接受的情况。
先决定方法、分隔符与斜杠的位置
typescript
type Method="get"|"post"|"put"|"delete";
type Endpoint=`/${string}`;
type Simple=`${Method}${Endpoint}`; // get/users,不是/get/users
type WithLeading=`/${Method}${Endpoint}`; // /get/users
type WithColon=`${Method}:${Endpoint}`; // get:/users
三种是不同契约,不能把一种模板配另一种输出。若保留/get/users形式,必须在模板前明确增加/。它们只是说明字符串形状,不执行HTTP请求、解析URL编码或控制服务端路由。
联合组合与自定义前后缀
typescript
type Row=`row${number}`;
type Variant="primary"|"secondary";type Size="sm"|"md"|"lg";
type ClassName=`btn-${Variant}-${Size}`; // 2×3六种
type Prefix<T extends string,P extends string>=`${P}${Capitalize<T>}`;
type Suffix<T extends string,S extends string>=`${Capitalize<T>}${S}`;
row${number}不是只匹配row0到row9或正整数,需求若限定行号应另外设计有限联合或运行时验证。多个联合展开可迅速增长;规模很大时先生成类型或简化接口,避免为了字符串约束制造难维护的组合。
完整核心源码与验证目标
展开查看收起
typescript
export {};
const upper:Uppercase<"hello">="HELLO";const lower:Lowercase<"HELLO">="hello";
const capital:Capitalize<"hello">="Hello";const uncapital:Uncapitalize<"Hello">="hello";
type EventName=`on${Capitalize<"click"|"focus">}`;
const event:EventName="onClick";
type Method="get"|"post"|"put"|"delete";type Endpoint=`/${string}`;
const leading:`/${Method}${Endpoint}`="/get/users";
const colon:`${Method}:${Endpoint}`="post:/users";
type ClassName=`btn-${"primary"|"secondary"}-${"sm"|"md"|"lg"}`;
const css:ClassName="btn-primary-md";
type Prefix<T extends string,P extends string>=`${P}${Capitalize<T>}`;
type Suffix<T extends string,S extends string>=`${Capitalize<T>}${S}`;
const handler:Prefix<"click","on">="onClick";const id:Suffix<"submit","Btn">="SubmitBtn";
console.log("蓝色天空网",upper,lower,capital,uncapital);
console.log(event,leading,colon,css,handler,id);
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
- 蓝色天空网 HELLO hello Hello hello
- onClick /get/users post:/users btn-primary-md onClick SubmitBtn
本章附件与实例包
课程关联工程包(登记关联72章) · 含当前章节或实例 · mbskycom202611a325.zip
常见错误与边界检查
- console.log类型名
- 模板路径与赋值斜杠不符
- number插值只允许个位整数的误解
- 类型格式等同真实URL/事件验证
- 庞大联合组合不计编译代价
技术规范与官方资料
练习与参考解答
为什么`${Method}${Endpoint}`不接受/get/users?
查看参考解答
Method从get等字符串开头,Endpoint只在它后面添加/;结果是get/users。需要前导/时应在整个模板开头加/。