ts类型编写时,可以像es6一样使用模板字符串,使用方式基本一致。
🌰 简单示例
WithAttr
为自定义类型,接受一个泛型K
,且K
要继承自字符串string
。 在接受到的K
值添加上 "Attr"
后返回新的类型
1 2
| type WithAttr<K extends string> = `${K}Attr` type Name = WithAttr<'name'>
|

针对字符串的处理,typescript还提供了对应内置方法
1
| type CapitalizeStr = Capitalize<'hello world'>
|
1
| type UncapitalizeStr = Uncapitalize<'HELLO WORLD'>
|
1
| type LowercaseStr = Lowercase<'HELLO WORLD'>
|
1
| type UppercaseStr = Uppercase<'hello world'>
|
💡 在模板字符串中使用
1 2
| type WithAttr<K extends string> = `${Capitalize<K>}Attr` type name = WithAttr<'name'>
|

💡 在循环中使用
使用 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>
|
