typescript中的模板字符串

1k words

ts类型编写时,可以像es6一样使用模板字符串,使用方式基本一致。

🌰 简单示例

WithAttr 为自定义类型,接受一个泛型K,且K要继承自字符串string。 在接受到的K值添加上 "Attr" 后返回新的类型

1
2
type WithAttr<K extends string> = `${K}Attr`
type Name = WithAttr<'name'> // nameAttr

简单示例

针对字符串的处理,typescript还提供了对应内置方法

  • Capitalize 首字母大写
1
type CapitalizeStr = Capitalize<'hello world'> // Hello world
  • Uncapitalize 首字母小写
1
type UncapitalizeStr = Uncapitalize<'HELLO WORLD'> // hELLO WORLD
  • Lowercase 全部转为小写
1
type LowercaseStr = Lowercase<'HELLO WORLD'> // hello world
  • Uppercase 全部转大写
1
type UppercaseStr = Uppercase<'hello world'> // HELLO WORLD

💡 在模板字符串中使用

1
2
type WithAttr<K extends string> = `${Capitalize<K>}Attr`
type name = WithAttr<'name'> // NameAttr

在模板字符串中使用

💡 在循环中使用

使用 as 关键字可以对获取到进行重写,将其当做字符串处理即可

1
2
3
4
5
6
7
8
9
10
11
type Person = {
name: string
sex: '男' | '女' | '保密'
age: number
}

type ListEners<T extends object> = {
[P in keyof T as `on${Capitalize<P & string>}Change`]: (val: T[P]) => void
}

type PersonEventMap = ListEners<Person>

在循环中使用