-
-
Notifications
You must be signed in to change notification settings - Fork 543
/
camel-case.d.ts
80 lines (65 loc) · 1.9 KB
/
camel-case.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
import type {SplitWords} from './split-words';
/**
CamelCase options.
@see {@link CamelCase}
*/
export type CamelCaseOptions = {
/**
Whether to preserved consecutive uppercase letter.
@default true
*/
preserveConsecutiveUppercase?: boolean;
};
/**
Convert an array of words to camel-case.
*/
type CamelCaseFromArray<
Words extends string[],
Options extends CamelCaseOptions,
OutputString extends string = '',
> = Words extends [
infer FirstWord extends string,
...infer RemainingWords extends string[],
]
? Options['preserveConsecutiveUppercase'] extends true
? `${Capitalize<FirstWord>}${CamelCaseFromArray<RemainingWords, Options>}`
: `${Capitalize<Lowercase<FirstWord>>}${CamelCaseFromArray<RemainingWords, Options>}`
: OutputString;
/**
Convert a string literal to camel-case.
This can be useful when, for example, converting some kebab-cased command-line flags or a snake-cased database result.
By default, consecutive uppercase letter are preserved. See {@link CamelCaseOptions.preserveConsecutiveUppercase preserveConsecutiveUppercase} option to change this behaviour.
@example
```
import type {CamelCase} from 'type-fest';
// Simple
const someVariable: CamelCase<'foo-bar'> = 'fooBar';
// Advanced
type CamelCasedProperties<T> = {
[K in keyof T as CamelCase<K>]: T[K]
};
interface RawOptions {
'dry-run': boolean;
'full_family_name': string;
foo: number;
BAR: string;
QUZ_QUX: number;
'OTHER-FIELD': boolean;
}
const dbResult: CamelCasedProperties<RawOptions> = {
dryRun: true,
fullFamilyName: 'bar.js',
foo: 123,
bar: 'foo',
quzQux: 6,
otherField: false
};
```
@category Change case
@category Template literal
*/
export type CamelCase<Type, Options extends CamelCaseOptions = {preserveConsecutiveUppercase: true}> = Type extends string
? string extends Type
? Type
: Uncapitalize<CamelCaseFromArray<SplitWords<Type extends Uppercase<Type> ? Lowercase<Type> : Type>, Options>>
: Type;