常见字面量类型
- 在 TypeScript 中,字面量不仅可以表示值,还可以表示类型,即所谓的字面量类型;
- TypeScript 支持 3 种字面量类型:字符串 字面量类型、数字 字面量类型、布尔 字面量类型,对应的字符串字面量、数字字面量、布尔字面量分别拥有与其值一样的字面量类型;
let str: 'hello world' = 'hello world'; let num: 996 = 996; let bool: true = true
字符串字面量
-
字符串字面量类型其实就是字符串常量,与字符串类型不同的是它是具体的值;
type Name = "TS"; const name1: Name = "test"; // error 不能将类型"test"分配给类型"TS" const name2: Name = "TS";
-
实际上,定义单个的字面量类型并没有太大用处,它的应用场景是可以把多个字面量类型组合成一个联合类型,用来描述拥有明确成员的实用的集合;
type Direction = "north" | "east" | "south" | "west"; function getDirectionFirstLetter(direction: Direction) { return direction.substr(0, 1); } getDirectionFirstLetter("test"); // error 类型"test"的参数不能赋给类型“Direction”的参数 getDirectionFirstLetter("east");
数字字面量
-
数字字面量类型和字符串字面量类型差不多,都是指定类型为具体的值:
type Age = 18; interface Info { name: string; age: Age; } const info: Info = { name: "TS", age: 28, // error 不能将类型“28”分配给类型“18” };
布尔字面量
-
布尔字面量和上面的两个类似,不在多说;
let success: true; let fail: false; let value: true | false;
-
由于布尔值只有 true 和 false 两种,所以以下两种类型意思一样的;
let value1: true | false; let value2: boolean;
带模板参数的字面量类型
带模板参数的模板字面量类型在 TypeScript 中是一种强大的类型工具,它允许开发者在类型系统中嵌入变量和表达式,从而生成新的类型;
这种类型基于字符串字面量类型,并通过联合类型扩展成多个字符串;
基本用法
-
模板字面量类型使用反引号 `` 包围字符串,并使用 ${} 来嵌入变量或表达式;
type World = "world"; type Greeting = `hello ${World}`; // 结果为 "hello world"
-
当模板中的变量是一个联合类型时,每一个可能的字符串字面量都会被表示;
type EmailLocaleIDs = "head" | "section"; type FooterLocaleIDs = "footer" | "body"; type AllLocaleIDs = `${EmailLocaleIDs}_id` | `${FooterLocaleIDs}_id`; // 结果为 "head_id" | "section_id" | "footer_id" | "body_id"
将模板字符串用于其它类型表达式
-
具有索引签名的接口类型:
type T1 = `a${string}c`; type T2 = { [s: T1]: number; abb: 5; abokn: boolean; }; // 测试 let obj: T2 = { abb: 5, abokn: true, }; obj.abcc = 12; // (index) T2[`a${string}c`]: number type P2 = T2[T1]; // number => 支持带有变量/参数的模板,但会预先检查 `keyof T1`
-
映射,作为索引签名:
type T1 = `a${string}c`; type T3 = { [k in T1]: number; 'abc': 1; // error: 映射的类型可能不声明属性或方法 };
实际应用场景
-
生成 CSS 类名/样式:可以根据组件的属性动态生成类名;
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 T0 = EventName<'foo'>; // 结果为 "fooChange"
-
国际化:根据语言环境动态生成不同的字符串字面量类型;
TypeScript👉 扩展类型-枚举
上一篇