提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
typescript高阶之模版字面量类型
前端必备工具推荐网站(免费图床、API和ChatAI等实用工具):
http://luckycola.com.cn/
前言
学习目标
1、模板字面量类型语法
2、模板字面量类型示例
一、模板字面量类型语法
模版字面量类型
// `${T}` // 对于模板字面量类型中的类型变量T只能是string、number、boolean、bigint
// 例子
type Direction = 'left' | 'right' | 'top' | 'bottom';
type CssPadding = `padding-${Direction}`; // "padding-left" | "padding-right" | "padding-top" | "padding-bottom"
type MarginPadding = `margin-${Direction}`;// "margin-left" | "margin-right" | "margin-top" | "margin-bottom"
// 例子
type EventName<T extends string> = `${T}Change`;
type Concat<T extends string, U extends string> = `${T}-${U}`;
type toString<T extends string | boolean | number | bigint> = `${T}`;
type T0 = EventName<'foo'>;// "fooChange"
type T1 = Concat<'hello', 'word'>; // "hello-word"
type T2 = toString<true>; // "true"
type T3 = toString<'hello' | false | 2222 | -1234n>; // "hello" | "false" | "2222" | "-1234"
二、模板字面量类型示例
1.减少重复代码、提高复用性
代码如下(示例):
// 例子
type Direction = 'left' | 'right' | 'top' | 'bottom';
type CssPadding = `padding-${Direction}`; // "padding-left" | "padding-right" | "padding-top" | "padding-bottom"
type MarginPadding = `margin-${Direction}`;// "margin-left" | "margin-right" | "margin-top" | "margin-bottom"
2.运算规则
1、单个占位符的联合类型自动展开(f分布式匹配原则)
//单个占位符的联合类型自动展开
// A | B | C ====> `[${T}]` ====> `[${A}]` | `[${B}]` |`[${C}]`
// 模板字面量与其他工具类型一起使用
type CetterName<T extends string> = `get${Capitalize<T>}`;
type Cases<T extends string> = `${Uppercase<T>}---${Lowercase<T>}----${Capitalize<T>}---${Uncapitalize<T>}`;
type T6 = CetterName<'name'>;// "getName"
type T7 = Cases<'bar'>;// "BAR---bar----Bar---bar"
2、多个占位符的联合类型解析为叉积
// 多个占位符的联合类型解析为叉积
// A | B 和 C| D ====> `${S1}-${S2}` ====> `${A}-${C}` | `${A}-${D}` | `${B}-${C}` | `${B}-${D}`
// 模版字面量类型与条件类型infer一起使用
type InferRoot<T> = T extends `${infer R}${Capitalize<Direction>}` ? R : T;
type T8 = InferRoot<'marginLeft'>;// "margin"
type T9 = InferRoot<'paddingTop'>;// "padding"