Last active
September 29, 2021 16:20
-
-
Save alii/f0521d7a856ad0954c194a8fbf97fc99 to your computer and use it in GitHub Desktop.
ridiculously type-safe Array<string>.join()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Joins a string array together with a given spacer. Ridiculously unecessarily type-safe! | |
* @param t The tuple/array of string items to join together | |
* @param s The spacer to go between each character | |
* @returns A joint string joined together | |
*/ | |
export function join<V extends string, Tuple extends Readonly<[V, ...V[]]>, Spacer extends string>( | |
t: Tuple, | |
s: Spacer | |
) { | |
return t.join(s) as JoinStrTuple<Writable<Tuple>, Spacer>; | |
} | |
type Writable<T> = { | |
-readonly [K in keyof T]: T[K]; | |
}; | |
type JoinStrTuple< | |
Tuple extends string[], | |
Spacer extends string = ' ', | |
Head extends string = '' | |
> = Tuple extends [infer F, ...infer L] | |
? Head extends '' | |
? JoinStrTuple<Extract<L, string[]>, Spacer, F & string> | |
: JoinStrTuple<Extract<L, string[]>, Spacer, `${Head}${Spacer}${F & string}`> | |
: Head; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
💀