首页 > 其他分享 >Typescript类型体操 - kebab case

Typescript类型体操 - kebab case

时间:2022-09-08 00:56:48浏览次数:123  
标签:case Typescript const kebab KebabCase FooBarBaz type

题目

中文

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;

在线演示

标签:case,Typescript,const,kebab,KebabCase,FooBarBaz,type
From: https://www.cnblogs.com/laggage/p/type-challenge-kebab-case.html

相关文章

  • Typescript类型体操 - String to Union
    题目中文实现一个将接收到的String参数转换为一个字母Union的类型。例如typeTest='123';typeResult=StringToUnion<Test>;//expectedtobe"1"|"2"|......
  • Typescript类型体操 - Absolute
    题目中文实现一个接收string,number或bigInt类型参数的Absolute类型,返回一个正数字符串。例如typeTest=-100;typeResult=Absolute<Test>;//expectedtobe"......
  • Typescript类型体操 - Append to object
    题目中文实现一个为接口添加一个新字段的类型。该类型接收三个参数,返回带有新字段的接口类型。例如:typeTest={id:'1'}typeResult=AppendToObject<Test,'va......
  • Typescript类型体操 - Flatten
    题目中文在这个挑战中,你需要写一个接受数组的类型,并且返回扁平化的数组类型。例如:typeflatten=Flatten<[1,2,[3,4],[[[5]]]]>//[1,2,3,4,5]EnglishIn......
  • Typescript类型体操 - Length of String
    题目中文计算字符串的长度,类似于String#length。EnglishComputethelengthofastringliteral,whichbehaveslikeString#length.答案解法1typeStringToArr......
  • [Typescript Challenges] 15. Medium - Omit
    Implementthebuilt-in Omit<T,K> genericwithoutusingit.Constructsatypebypickingallpropertiesfrom T andthenremoving KForexampleinterfaceT......
  • Typescript类型体操 - Append Argument
    题目中文实现一个泛型AppendArgument<Fn,A>,对于给定的函数类型Fn,以及一个任意类型A,返回一个新的函数G。G拥有Fn的所有参数并在末尾追加类型为A的参数。typeF......
  • Typescript类型体操 - Parameters
    题目中文实现内置的Parameters<T>类型,而不是直接使用它,可参考TypeScript官方文档。例如:constfoo=(arg1:string,arg2:number):void=>{}typeFunctionParams......
  • Typescript类型体操 - ReplaceAll
    答案中文实现ReplaceAll<S,From,To>将一个字符串S中的所有子字符串From替换为To。例如typereplaced=ReplaceAll<'types','',''>//期望是'types'......
  • Typescript类型体操 - Replace
    题目中文实现Replace<S,From,To>将字符串S中的第一个子字符串From替换为To。例如typereplaced=Replace<'typesarefun!','fun','awesome'>//期望是......