-
-
Notifications
You must be signed in to change notification settings - Fork 594
/
Copy pathsplit.d.ts
88 lines (70 loc) · 2.61 KB
/
split.d.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import type {And} from './and';
import type {ApplyDefaultOptions, Not} from './internal';
import type {IsStringLiteral} from './is-literal';
import type {Or} from './or';
/**
Split options.
@see {@link Split}
*/
type SplitOptions = {
/**
When enabled, instantiations with non-literal string types (e.g., `string`, `Uppercase<string>`, `on${string}`) simply return back `string[]` without performing any splitting, as the exact structure cannot be statically determined.
Note: In the future, this option might be enabled by default, so if you currently rely on this being disabled, you should consider explicitly enabling it.
@default false
@example
```ts
type Example1 = Split<`foo.${string}.bar`, '.', {strictLiteralChecks: false}>;
//=> ['foo', string, 'bar']
type Example2 = Split<`foo.${string}`, '.', {strictLiteralChecks: true}>;
//=> string[]
type Example3 = Split<'foobarbaz', `b${string}`, {strictLiteralChecks: false}>;
//=> ['foo', 'r', 'z']
type Example4 = Split<'foobarbaz', `b${string}`, {strictLiteralChecks: true}>;
//=> string[]
```
*/
strictLiteralChecks?: boolean;
};
type DefaultSplitOptions = {
strictLiteralChecks: false;
};
/**
Represents an array of strings split using a given character or character set.
Use-case: Defining the return type of a method like `String.prototype.split`.
@example
```
import type {Split} from 'type-fest';
declare function split<S extends string, D extends string>(string: S, separator: D): Split<S, D>;
type Item = 'foo' | 'bar' | 'baz' | 'waldo';
const items = 'foo,bar,baz,waldo';
let array: Item[];
array = split(items, ',');
```
@see {@link SplitOptions}
@category String
@category Template literal
*/
export type Split<
S extends string,
Delimiter extends string,
Options extends SplitOptions = {},
> =
SplitHelper<S, Delimiter, ApplyDefaultOptions<SplitOptions, DefaultSplitOptions, Options>>;
type SplitHelper<
S extends string,
Delimiter extends string,
Options extends Required<SplitOptions>,
Accumulator extends string[] = [],
> = S extends string // For distributing `S`
? Delimiter extends string // For distributing `Delimeter`
// If `strictLiteralChecks` is `false` OR `S` and `Delimiter` both are string literals, then perform the split
? Or<Not<Options['strictLiteralChecks']>, And<IsStringLiteral<S>, IsStringLiteral<Delimiter>>> extends true
? S extends `${infer Head}${Delimiter}${infer Tail}`
? SplitHelper<Tail, Delimiter, Options, [...Accumulator, Head]>
: Delimiter extends ''
? Accumulator
: [...Accumulator, S]
// Otherwise, return `string[]`
: string[]
: never // Should never happen
: never; // Should never happen