I’m trying to improve my knowledge of types in typescript, so I’m doing some type challenges. One of the challenges is to make a type that capitalises a generic string, as shown below (here).
type capitalized = CapitalizeWords<'hello world, my friends'> // expected to be 'Hello World, My Friends'
Although I have solved this now, my first attempt resulted in type instatiation too deep and possibly infinite
. I redid the problem with some online help, but just looking at the code differences, the their is the same amount of recursion. As a result, I don’t understand why one fails, and the other succeeds. I also suspect that for a sufficiently large string, the second type will also fail. However, I don’t know how to predict how long a string would make it fail.
This was my first attempt at making a capitalised words type.
type CapitalizeWords<S extends string, C extends boolean = true> =
S extends `${infer A}${infer B}`
? Lowercase<A> extends Uppercase<A>
? `${A}${CapitalizeWords<B, true>}`
: C extends true
? `${Uppercase<A>}${CapitalizeWords<B, false>}`
: `${A}${CapitalizeWords<B, false>}`
: S
It works on small strings, (e.g. hello world
), but fails with longer strings (e.g.aa!bb@cc#dd$ee%ff^gg&hh*ii(jj)kk_ll+mm{nn}oo|pp????qq
) with type instatiation too deep and possibly infinite
. My second attempt, with some online help, was:
type CapitalizeWords<S extends string, W extends string = ""> =
S extends `${infer A}${infer B}`
? Lowercase<A> extends Uppercase<A>
? `${Capitalize<W>}${A}${CapitalizeWords<B>}`
: CapitalizeWords<B, `${W}${A}`>
: Capitalize<W>
This works for the longer string. However, this looks like the same level of recursion to me (one level per char), so I don’t understand why this one is fine.
Looking elsewhere online, this question (and others) sidesteps the issue and simply cuts the level of recursion, or defering evaluation. This does not help me predict why different methods may be more forgiving, or how much recursion I can allow.
Crunchy Carrots is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.