Typescript类型体操 - kebab case
题目
中文
将 camelCase 或 PascalCase 的字符串转换为 kebab-case 的风格
示例:
type FooBarBaz = KebabCase<'FooBarBaz'>;
const foobarbaz: FooBarBaz = 'foo-bar-baz';
type DoNothing = KebabCase<'do-nothing'>;
const doNothing: DoNothing = 'do-nothing';
English
Replace the camelCase or PascalCase string with kebab-case.
FooBarBaz -> foo-bar-baz
For example
type FooBarBaz = KebabCase<'FooBarBaz'>;
const foobarbaz: FooBarBaz = 'foo-bar-baz';
type DoNothing = KebabCase<'do-nothing'>;
const doNothing: DoNothing = 'do-nothing';
答案
type KebabCase<
S extends string,
TLastWord extends string = ''
> = S extends `${infer L}${infer R}`
? Lowercase<`${Lowercase<L> extends L
? L
: TLastWord extends ''
? L
: `-${L}`}${KebabCase<R, L>}`>
: S;
浙公网安备 33010602011771号