Created
November 5, 2021 11:41
-
-
Save maxhilliard/a3dd05b8b4549910682163a2e47d3150 to your computer and use it in GitHub Desktop.
Utility types to improve JS's native `.split` and `.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
// So let's say we have a string of known parts, Str | |
type Foo = 'foo' | |
type Bar = 'bar' | |
type Baz = 'baz' | |
type Str = `${Foo}.${Bar}.${Baz}` | |
const str: Str = 'foo.bar.baz' | |
// I want to split it into the known parts, | |
// Which I can do in a nice way with this Split type | |
type Split<S extends string, D extends string> = S extends "" | |
? [] | |
: S extends `${infer T}${D}${infer U}` | |
? [T, ...Split<U, D>] | |
: [S]; | |
// Now splitStr is typed as a tuple, which is nice | |
const splitStr = str.split('.') as Split<typeof str, '.'> | |
// The Join type joins an array to a string literal | |
type Join<Arr extends any[], Joiner extends string> = | |
Arr["length"] extends 1 | |
? `${Arr[0]}` | |
: Arr extends [string, ...infer R] | |
? `${Arr[0]}${Joiner}${Join<R, Joiner>}` | |
: never | |
// joined now has type 'foo.bar.baz' instead of string that the native .join method gives us | |
const joined = splitStr.join('.') as Join<typeof splitStr, '.'> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment