-
-
Notifications
You must be signed in to change notification settings - Fork 546
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
4 changed files
with
43 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
/** | ||
Join an array of strings using the given string as delimiter. | ||
Use-case: Defining key paths in a nested object. For example, for dot-notation fields in MongoDB queries. | ||
@example | ||
``` | ||
import {Join} from 'type-fest'; | ||
const path: Join<['foo', 'bar', 'baz'], '.'> = ['foo', 'bar', 'baz'].join('.'); | ||
``` | ||
@category Template Literals | ||
*/ | ||
export type Join< | ||
Strings extends string[], | ||
Delimiter extends string, | ||
> = Strings extends [] ? '' : | ||
Strings extends [string] ? `${Strings[0]}` : | ||
// @ts-expect-error `Rest` is inferred as `unknown` here: https://github.com/microsoft/TypeScript/issues/45281 | ||
Strings extends [string, ...infer Rest] ? `${Strings[0]}${Delimiter}${Join<Rest, Delimiter>}` : | ||
string; |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
import {expectError, expectType} from 'tsd'; | ||
import {Join} from '../index'; | ||
|
||
// General use. | ||
const generalTest: Join<['foo', 'bar', 'baz'], '.'> = 'foo.bar.baz'; | ||
expectType<'foo.bar.baz'>(generalTest); | ||
expectError<'foo'>(generalTest); | ||
expectError<'foo.bar'>(generalTest); | ||
expectError<'foo.bar.ham'>(generalTest); | ||
|
||
// Empty string delimiter. | ||
const emptyDelimiter: Join<['foo', 'bar', 'baz'], ''> = 'foobarbaz'; | ||
expectType<'foobarbaz'>(emptyDelimiter); | ||
expectError<'foo.bar.baz'>(emptyDelimiter); | ||
|
||
// Empty input. | ||
const emptyInput: Join<[], '.'> = ''; | ||
expectType<''>(emptyInput); | ||
expectError<'foo'>(emptyInput); |