Typescript类型体操 - kebab case

题目

中文

camelCasePascalCase 的字符串转换为 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;

在线演示

posted @ 2022-09-08 00:31  Laggage  阅读(81)  评论(0编辑  收藏  举报