### Longest Common Prefix Master advanced TypeScript type manipulation in this medium-level challenge on TypeScriptPro.
In this medium-level challenge, you'll implement LongestCommonPrefix, a type that finds the longest common prefix string shared among all strings in a given tuple, returning an empty string if no common prefix exists.
Write a type, LongestCommonPrefix that returns the longest common prefix string amongst a tuple of strings.
If there is no common prefix, return an empty string "".
type Common = LongestCommonPrefix<["flower", "flow", "flight"]>
// ?^ "fl"
type Uncommon = LongestCommonPrefix<["dog", "racecar", "race"]>
// ?^ ""Inspired by LeetCode 14. Longest Common Prefix
Change the following code to make the test cases pass (no type check errors).
type LongestCommonPrefix<
T extends string[],
Prefix extends string = ''
> = T extends [infer First extends string, ...infer Rest extends string[]]
? First extends `${Prefix}${infer C}${string}`
? AllStartWith<Rest, `${Prefix}${C}`> extends true
? LongestCommonPrefix<T, `${Prefix}${C}`>
: Prefix
: Prefix
: Prefix;
type AllStartWith<T extends string[], P extends string> =
T extends [infer First extends string, ...infer Rest extends string[]]
? First extends `${P}${string}`
? AllStartWith<Rest, P>
: false
: true;How it works:
LongestCommonPrefix takes the first string from the tuple and attempts to extend the current Prefix by one character at a time using template literal inference (${Prefix}${infer C}${string})AllStartWith checks whether every remaining string in the tuple starts with the candidate prefix, returning true only if all strings match${Prefix}${infer C}${string} when the prefix is non-emptyThis challenge helps you understand recursive template literal type manipulation and tuple iteration, and how to apply these concepts in real-world scenarios.
This challenge is originally from here.
Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.
Only 27 Spots left
Get 1 month early access
Pre-Launch discount