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