forked from sindresorhus/type-fest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
replace.d.ts
67 lines (55 loc) · 1.47 KB
/
replace.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
type ReplaceOptions = {
all?: boolean;
};
/**
Represents a string with some or all matches replaced by a replacement.
Use-case:
- `snake-case-path` to `dotted.path.notation`
- Changing date/time format: `01-08-2042` → `01/08/2042`
- Manipulation of type properties, for example, removal of prefixes
@example
```
import {Replace} from 'type-fest';
declare function replace<
Input extends string,
Search extends string,
Replacement extends string
>(
input: Input,
search: Search,
replacement: Replacement
): Replace<Input, Search, Replacement>;
declare function replaceAll<
Input extends string,
Search extends string,
Replacement extends string
>(
input: Input,
search: Search,
replacement: Replacement
): Replace<Input, Search, Replacement, {all: true}>;
// The return type is the exact string literal, not just `string`.
replace('hello ?', '?', '🦄');
//=> 'hello 🦄'
replace('hello ??', '?', '❓');
//=> 'hello ❓?'
replaceAll('10:42:00', ':', '-');
//=> '10-42-00'
replaceAll('__userName__', '__', '');
//=> 'userName'
replaceAll('My Cool Title', ' ', '');
//=> 'MyCoolTitle'
```
@category String
@category Template literal
*/
export type Replace<
Input extends string,
Search extends string,
Replacement extends string,
Options extends ReplaceOptions = {},
> = Input extends `${infer Head}${Search}${infer Tail}`
? Options['all'] extends true
? `${Head}${Replacement}${Replace<Tail, Search, Replacement, Options>}`
: `${Head}${Replacement}${Tail}`
: Input;