1 | import {WordSeparators} from '../source/utilities';
|
---|
2 | import {Split} from './utilities';
|
---|
3 |
|
---|
4 | /**
|
---|
5 | Step by step takes the first item in an array literal, formats it and adds it to a string literal, and then recursively appends the remainder.
|
---|
6 |
|
---|
7 | Only to be used by `CamelCaseStringArray<>`.
|
---|
8 |
|
---|
9 | @see CamelCaseStringArray
|
---|
10 | */
|
---|
11 | type InnerCamelCaseStringArray<Parts extends any[], PreviousPart> =
|
---|
12 | Parts extends [`${infer FirstPart}`, ...infer RemainingParts]
|
---|
13 | ? FirstPart extends undefined
|
---|
14 | ? ''
|
---|
15 | : FirstPart extends ''
|
---|
16 | ? InnerCamelCaseStringArray<RemainingParts, PreviousPart>
|
---|
17 | : `${PreviousPart extends '' ? FirstPart : Capitalize<FirstPart>}${InnerCamelCaseStringArray<RemainingParts, FirstPart>}`
|
---|
18 | : '';
|
---|
19 |
|
---|
20 | /**
|
---|
21 | Starts fusing the output of `Split<>`, an array literal of strings, into a camel-cased string literal.
|
---|
22 |
|
---|
23 | It's separate from `InnerCamelCaseStringArray<>` to keep a clean API outwards to the rest of the code.
|
---|
24 |
|
---|
25 | @see Split
|
---|
26 | */
|
---|
27 | type CamelCaseStringArray<Parts extends string[]> =
|
---|
28 | Parts extends [`${infer FirstPart}`, ...infer RemainingParts]
|
---|
29 | ? Uncapitalize<`${FirstPart}${InnerCamelCaseStringArray<RemainingParts, FirstPart>}`>
|
---|
30 | : never;
|
---|
31 |
|
---|
32 | /**
|
---|
33 | Convert a string literal to camel-case.
|
---|
34 |
|
---|
35 | This can be useful when, for example, converting some kebab-cased command-line flags or a snake-cased database result.
|
---|
36 |
|
---|
37 | @example
|
---|
38 | ```
|
---|
39 | import {CamelCase} from 'type-fest';
|
---|
40 |
|
---|
41 | // Simple
|
---|
42 |
|
---|
43 | const someVariable: CamelCase<'foo-bar'> = 'fooBar';
|
---|
44 |
|
---|
45 | // Advanced
|
---|
46 |
|
---|
47 | type CamelCasedProps<T> = {
|
---|
48 | [K in keyof T as CamelCase<K>]: T[K]
|
---|
49 | };
|
---|
50 |
|
---|
51 | interface RawOptions {
|
---|
52 | 'dry-run': boolean;
|
---|
53 | 'full_family_name': string;
|
---|
54 | foo: number;
|
---|
55 | }
|
---|
56 |
|
---|
57 | const dbResult: CamelCasedProps<ModelProps> = {
|
---|
58 | dryRun: true,
|
---|
59 | fullFamilyName: 'bar.js',
|
---|
60 | foo: 123
|
---|
61 | };
|
---|
62 | ```
|
---|
63 | */
|
---|
64 | export type CamelCase<K> = K extends string ? CamelCaseStringArray<Split<K, WordSeparators>> : K;
|
---|