Skip to content

Instantly share code, notes, and snippets.

@alii
Last active September 29, 2021 16:20
Show Gist options
  • Save alii/f0521d7a856ad0954c194a8fbf97fc99 to your computer and use it in GitHub Desktop.
Save alii/f0521d7a856ad0954c194a8fbf97fc99 to your computer and use it in GitHub Desktop.
ridiculously type-safe Array<string>.join()
/**
* 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;
@Phineas
Copy link

Phineas commented Sep 29, 2021

image

@pxseu
Copy link

pxseu commented Sep 29, 2021

image
💀

@alii
Copy link
Author

alii commented Sep 29, 2021

@pxseu @Phineas hi guys!!!!!!!!!!!!!!!!!!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment