Implement CapitalizeWords<T>
which converts the first letter of each word of a string to uppercase and leaves the rest as-is.
For example
type capitalized = CapitalizeWords<'hello world, my friends'> // expected to be 'Hello World, My Friends'
/* _____________ Your Code Here _____________ */
type StringToUnion<T extends string> = T extends `${infer F}${infer R}` ? F | StringToUnion<R> : never;
type LowerLetterUnion = StringToUnion<'abcdefghijklmnopqrstuvwxyz'>;
type UpperLetterUnion = Uppercase<LowerLetterUnion>;
type CapitalizeWords<S extends string, Prev extends string = '', ACC extends string = ''> = S extends `${infer First}${infer REST}`
? Uppercase<Prev> extends UpperLetterUnion // only symbols and space cannnot be uppercased
? CapitalizeWords<REST, First, `${ACC}${First}`> // prev is char, the follow char not need to be uppercased
: CapitalizeWords<REST, First, `${ACC}${Uppercase<First>}`> // pre is symbol, current char should be uppercased
: ACC;
/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '@type-challenges/utils'
type cases = [
Expect<Equal<CapitalizeWords<'foobar'>, 'Foobar'>>,
Expect<Equal<CapitalizeWords<'FOOBAR'>, 'FOOBAR'>>,
Expect<Equal<CapitalizeWords<'foo bar'>, 'Foo Bar'>>,
Expect<Equal<CapitalizeWords<'foo bar hello world'>, 'Foo Bar Hello World'>>,
Expect<Equal<CapitalizeWords<'foo bar.hello,world'>, 'Foo Bar.Hello,World'>>,
Expect<Equal<CapitalizeWords<'aa!bb@cc#dd$ee%ff^gg&hh*ii(jj)kk_ll+mm{nn}oo|pp
标签:Typescript,_____________,Capitalize,Expect,Words,StringToUnion,CapitalizeWords,t
From: https://www.cnblogs.com/Answer1215/p/16880740.html