Implement type CheckRepeatedChars<S> which will return whether type S contains duplicated chars. Learn union type manipulation in this medium-level challenge on TypeScriptPro.
In this medium-level challenge, you'll implement CheckRepeatedChars<S> which checks whether a string type contains any duplicated characters, returning true or false.
Implement type CheckRepeatedChars<S> which will return whether type S contains duplicated chars?
For example:
type CheckRepeatedChars<'abc'> // false
type CheckRepeatedChars<'aba'> // trueChange the following code to make the test cases pass (no type check errors).
Launch price: $19 $29
One-time payment. Lifetime access to all pro challenges.
type CheckRepeatedChars<T extends string> =
T extends `${infer First}${infer Rest}`
? Rest extends `${string}${First}${string}`
? true
: CheckRepeatedChars<Rest>
: falseHow it works:
T extends `${infer First}${infer Rest}` splits the string into its first character First and the remaining string RestRest extends `${string}${First}${string}` checks whether First appears anywhere in the remaining string Rest by matching it with arbitrary strings on both sidestrue since a duplicate existsCheckRepeatedChars<Rest> to check subsequent charactersfalse, meaning no duplicates were foundThis challenge helps you understand template literal type pattern matching and recursive string analysis, and how to apply these concepts in real-world scenarios.
This challenge is originally from here.
Get the latest TypeScript tips, tutorials, and updates delivered straight to your inbox.