目录 (10)
[Typescript] Template Literal Types
我打算把 TypeScript 的功能逐一拿出来讲一讲。第一个被选中的功能就是 Template Literal Types。literal types 本身并不难,但 2. 应用示例 需要先了解 Generic Type 和 Type infer 才比较好理解。
1. Literal 类型与 Template Literal 类型
Template Literal 类型是一种能把字符串字面量写成模板字符串形式(反引号 ``)并组合起来使用的类型。
Template Literal 类型和 String Literal 类型可以用在各种场景中,比如按照字符串规则生成设计令牌(design token),或者根据 Object 的 key 值自动生成类型。下面是对各个类型的说明。
Literal Type:不只是 string、number 这样的普通类型,而是把特定的字符串或数字指定为类型的类型。
type Direction = "left" | "right";const direction:Direction = "left"; ✅const direction:Direction = "up"; ❌ // 只能取 left 和 right 两个值。Type '"up"' is not assignable to type '"left" | "right"'const direction:string = "up"; ✅ // string 类型可以是任意字符串。Template Literal:用模板字符串形式(反引号 ``)组合 String Literal 而成的类型。
type Fruit = "apple" | "banana" | "mango";type Sentence = `I like ${Fruit}`;const sentence:Sentence = "I like apple"; ✅const sentence:Sentence = "I hate apple"; ❌ // 不是 I like。Type '"I hate apple"' is not assignable to type '"I like apple" | "I like banana" | "I like mango"'.const sentence:Sentence = "I like melon"; ❌ // 是 Fruit 类型中没有的水果。Type '"I like melon"' is not assignable to type '"I like apple" | "I like banana" | "I like mango"'.2. Template Literal 应用示例
下面通过示例来展示 Template Literal 可以用在哪些场景。我准备了 1 个自己用过 Template Literal 的例子,以及 1 个官方文档中的应用示例。
2.1 设计令牌 - Typography
我曾在设计系统中用这个功能来定义遵循 {type}-{Size}-{Weight} 规则的 Typography 设计令牌。下面是示例代码。
type FontType = "title" | "body";type FontSize = "sm" | "md" | "lg";type FontWeight = "regular" | "medium" | "bold";type FontVariant = `${FontType}-${FontSize}-${FontWeight}`; // FontType 2种 FontSize 3种 * FontWeight 3种 = 18种;// "title-sm-regular", "title-md-regular", "title-md-bold", "title-md-regular...等共 18 种字符串联合类型会被生成。type FontProperties = Pick< CSSProperties, "fontWeight" | "lineHeight" | "fontSize" | "letterSpacing">;type Typography = Record<FontVariant, FontProperties>;const typography: Typography = { "body-lg-bold": { fontSize: "1rem", fontWeight: 700, letterSpacing: 0, lineHeight: 1, }, "body-lg-medium": { fontSize: "1rem", fontWeight: 500, letterSpacing: 0, lineHeight: 1, }, //...};如果想让 Typography 类型约束得更严格,还可以进一步扩展。下面是根据 FontWeight 自动固定 CSS fontWeight 类型的示例。
import {CSSProperties} from "react";type FontType = "title" | "body";type FontSize = "sm" | "md" | "lg";type FontWeightValueMap = { regular: 400; medium: 500; bold: 700;};// 如果也想作为变量使用,就用 const fontWeightValueMap 创建变量来使用,再用 typeof 关键字获取类型。type FontWeight = keyof FontWeightValueMap; // "regular" | "medium" | "bold"type FontWeightCSSProperty<FW extends FontWeight> = { fontWeight: FontWeightValueMap[FW];}; //根据 FontWeight 将值固定为 CSS literal type number。type FontVariant = `${FontType}-${FontSize}-${FontWeight}`; // 18 种令牌type ExtractFontWeight<FV extends FontVariant> = FV extends `${string}-${string}-${infer FW}` ? FW : never; // 从 FontVariant 中提取 FontWeighttype FontProperties<FV extends FontVariant> = Pick< CSSProperties, "lineHeight" | "fontSize" | "letterSpacing"> & FontWeightCSSProperty<ExtractFontWeight<FV>>; //fontWeight 的值由 Font Variant 中的 Font Weight 决定。type Typography = { [key in FontVariant]: FontProperties<key>;};const typography: Typography = { "body-lg-bold": { fontSize: "1rem", fontWeight: 700, ✅ letterSpacing: 0, lineHeight: 1, }, "body-lg-medium": { fontSize: "1rem", fontWeight: 700, ❌ medium 的值必须是 500,所以会报类型错误。Type '700' is not assignable to type '500' letterSpacing: 0, lineHeight: 1, }, //...};如果问在设计系统中这两种类型设置方法哪个更好,那要看你想获得什么样的好处,或者取决于具体情况。如果设计令牌的结构以后不打算再改动,或者是很快就要结束的项目,那么在类型上花心思只是浪费时间。但如果是要长期重点使用的设计系统,甚至考虑到与 Figma 联动来做版本管理和自动同步到 Figma,那么按照明确的设计规划来设置类型似乎更好。总之,我认为最好根据可用人力、熟练度、空闲时间等情况来决定。
2.2 官方文档示例
下面是官方文档中的一个示例:根据 object 的 literal 键值及其 value 的类型,自动生成函数的类型。即使 object 的 value 类型多种多样,开发者也可以方便地使用匹配好的类型来编写代码。
type PropEventSource<T> = { on<Key extends string & keyof T> (eventName: `${Key}Changed`, callback: (newValue: T[Key]) => void): void;};// ${T 的 key 值} + "Changed" 会成为 eventName。callback 的 newValue 会成为 ${与 T 的 key 值匹配的 value 的类型}/// Create a "watched object" with an `on` method/// so that you can watch for changes to properties.declare function makeWatchedObject<T>(obj: T): Type & PropEventSource<T>;const person = makeWatchedObject({ firstName: "Saoirse", lastName: "Ronan", age: 26});person.on("firstNameChanged", (newName) => {console.log(newName)});// on 函数的第 1 个参数是 `{key}Changed`,第 2 个参数(函数)的 newName 会自动成为 string 类型。 person.on("ageChanged", newAge => {console.log(newAge)})// 同样,${person 的 key 值 = "age"}+"Changed",newAge 是 person["age"] 的类型。3. 相关工具类型
下面是与 Template Literal、String Literal 相关的工具类型,摘自官方文档。
3.1 Uppercase
将所有字符转换为大写类型的工具类型。
type Greeting = "Hello, world"type ShoutyGreeting = Uppercase<Greeting> // "HELLO, WORLD" 类型type ASCIICacheKey<Str extends string> = `ID-${Uppercase<Str>}`type MainID = ASCIICacheKey<"my_app"> // "ID-MY_APP" 类型3.2 Lowercase
将所有字符转换为小写类型的工具类型。
type Greeting = "Hello, world"type QuietGreeting = Lowercase<Greeting> // "hello, world" 类型type ASCIICacheKey<Str extends string> = `id-${Lowercase<Str>}`type MainID = ASCIICacheKey<"MY_APP"> // "id-my_app" 类型3.3 Capitalize
将首字母转换为大写类型的工具类型。
type Greeting = "hello, world"type ShoutyGreeting = Uppercase<Greeting> // "Hello, world" 类型3.4 Uncapitalize
将首字母转换为小写类型的工具类型
type Greeting = "HELLO WORLD"type ShoutyGreeting = Uppercase<Greeting> // "hELLO WORLD" 类型