将 camelCase
(小驼峰)或 PascalCase
(大驼峰)字符串替换为 kebab-case
例如:
type FooBarBaz = KebabCase<"FooBarBaz">
const foobarbaz: FooBarBaz = "foo-bar-baz"
type DoNothing = KebabCase<"do-nothing">
const doNothing: DoNothing = "do-nothing"
答案
// 方法 1 type KebabCase<S extends string> = S extends `${infer L}${infer R}` ? R extends Uncapitalize<R> ? `${Lowercase<L>}${KebabCase<R>}` : `${Lowercase<L>}-${KebabCase<R>}` : '' // 方法 2 type KebabCase<S extends string, Before extends string = ''> = S extends `${infer L}${infer R}` ? L extends Lowercase<L> // 除大写字母 ? KebabCase<R, `${Before}${L}`> : Before extends '' ? KebabCase<R, Lowercase<L>> : KebabCase<R, `${Before}-${Lowercase<L>}`> : Before