UNPKG

2.85 kBTypeScriptView Raw
1// The builtin `join` method supports all these natively in the same way that typescript handles them so we can safely accept all of them.
2type JoinableItem = string | number | bigint | boolean | undefined | null;
3
4// `null` and `undefined` are treated uniquely in the built-in join method, in a way that differs from the default `toString` that would result in the type `${undefined}`. That's why we need to handle it specifically with this helper.
5// @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join#description
6type NullishCoalesce<
7 Value extends JoinableItem,
8 Fallback extends string,
9> = Value extends undefined | null ? NonNullable<Value> | Fallback : Value;
10
11/**
12Join an array of strings and/or numbers using the given string as a delimiter.
13
14Use-case: Defining key paths in a nested object. For example, for dot-notation fields in MongoDB queries.
15
16@example
17```
18import type {Join} from 'type-fest';
19
20// Mixed (strings & numbers) items; result is: 'foo.0.baz'
21const path: Join<['foo', 0, 'baz'], '.'> = ['foo', 0, 'baz'].join('.');
22
23// Only string items; result is: 'foo.bar.baz'
24const path: Join<['foo', 'bar', 'baz'], '.'> = ['foo', 'bar', 'baz'].join('.');
25
26// Only number items; result is: '1.2.3'
27const path: Join<[1, 2, 3], '.'> = [1, 2, 3].join('.');
28
29// Only bigint items; result is '1.2.3'
30const path: Join<[1n, 2n, 3n], '.'> = [1n, 2n, 3n].join('.');
31
32// Only boolean items; result is: 'true.false.true'
33const path: Join<[true, false, true], '.'> = [true, false, true].join('.');
34
35// Contains nullish items; result is: 'foo..baz..xyz'
36const path: Join<['foo', undefined, 'baz', null, 'xyz'], '.'> = ['foo', undefined, 'baz', null, 'xyz'].join('.');
37
38// Partial tuple shapes (rest param last); result is: `prefix.${string}`
39const path: Join<['prefix', ...string[]], '.'> = ['prefix'].join('.');
40
41// Partial tuple shapes (rest param first); result is: `${string}.suffix`
42const path: Join<[...string[], 'suffix'], '.'> = ['suffix'].join('.');
43
44// Tuples items with nullish unions; result is '.' | 'hello.' | '.world' | 'hello.world'
45const path: Join<['hello' | undefined, 'world' | null], '.'> = ['hello', 'world'].join('.');
46```
47
48@category Array
49@category Template literal
50*/
51export type Join<
52 Items extends readonly JoinableItem[],
53 Delimiter extends string,
54> = Items extends readonly []
55 ? ''
56 : Items extends readonly [JoinableItem?]
57 ? `${NullishCoalesce<Items[0], ''>}`
58 : Items extends readonly [
59 infer First extends JoinableItem,
60 ...infer Tail extends readonly JoinableItem[],
61 ]
62 ? `${NullishCoalesce<First, ''>}${Delimiter}${Join<Tail, Delimiter>}`
63 : Items extends readonly [
64 ...infer Head extends readonly JoinableItem[],
65 infer Last extends JoinableItem,
66 ]
67 ? `${Join<Head, Delimiter>}${Delimiter}${NullishCoalesce<Last, ''>}`
68 : string;