【Typescript 系列】第十四节:模板字面量

120 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第17天,点击查看活动详情

1. 引言

今天我们来介绍下TypeScript类型系统中模板字面量,它和JavaScript中的模板字面量如出一辙。我们先来了解下什么是模板字面量

2. 含义

模板字面量类型以++字符串字面量++类型为基础,可以通过联合类型扩展成多个字符串。它在类型系统操作使用中和JavaScript中的模板字面量使用相同的语法,通过传入的模板的变量不同,返回拼接不同的字符串字面量:(请看例子一)

3. 作用

  • 当我们使用到一些有着重复字符串的类型变量时,可以使用模板字面量类型减少重复代码。
  • 如果但我们传入的字符串字面量为联合类型时,就会触发分布式条件类型语法(请看例子二)
  • 但我们有一个对象里面拥有着固定属性,当我们想要有个对象方法里面存放着获取该对象的属性值的方法时,就可以配合类型重映射加上类型断言as语法 的方式改造该类型。(请看例子三)
  • 如果是多个类型占位符,则解析为多个类型占位符的联合类型(请看例子四)
  • 还可以配合infer做类型推导(请看例子五)

4. 例子

例子一:

type SayWord<T extends string> = () => `hello,${T}`
type Show = SayWord<'guozi'> // type Show = () => "hello,guozi"
type Show2 = SayWord<'guozizz'> // type Show = () => "hello,guozizz"

例子二:

type SayWord<T extends string> = () => `hello,${T}`
type Show3 = SayWord<'guozi' | 'guozizz' | 'guoziwww' | 'guozihhhh'> // type Show3 = () => "hello,guozi" | "hello,guozizz" | "hello,guoziwww" | "hello,guozihhhh"

例子三:

type User = {
    name: string,
    age: number
}
type GetUser = {
    getName: ()=> string,
    getAge: ()=> number
}

type SetFun<T> = {
    [K in keyof T as `get${Capitalize<K & string>}`]: () => T[K]
}
type GetUserDemo = SetFun<User> 
// type GetUserDemo = {
//     getName: () => string;
//     getAge: () => number;
// } 

例子四:

type Getter2<T extends string,U extends string> = `${T | U},${U | T}`
type GetVal = Getter2<'jiang','zjamh'> // type GetVal = "jiang,jiang" | "jiang,zjamh" | "zjamh,jiang" | "zjamh,zjamh"

例子五:

type Dirction = 'left' | 'right' | 'top' | 'bottom'
type PaddingDirction = 'paddingLeft' | 'paddingRight' | 'paddingTop' | 'paddingBottom'
type MarginDirction = 'marginLeft' | 'marginRight' | 'marginTop' | 'marginBottom'
type GetDirctions<T,U> = U extends `${infer R }${Capitalize<T & string>}` ? R : never
type Introduction = GetDirctions<Dirction,PaddingDirction> // type Introduction = "padding"
type Introduction2 = GetDirctions<Dirction,MarginDirction> // type Introduction2 = "margin"

5. 总结

模板类型字面量让TypeScript 类型操作定义更加灵活多变,优化代码体积,减少重复代码书写,通过其他类型操作的配合使用能给开发带来诸多便利。