source: node_modules/type-fest/ts41/camel-case.d.ts

main
Last change on this file was d24f17c, checked in by Aleksandar Panovski <apano77@…>, 16 months ago

Initial commit

  • Property mode set to 100644
File size: 2.1 KB
Line 
1import {WordSeparators} from '../source/utilities';
2
3/**
4Recursively 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*/
6export 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/**
13Step 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
15Only to be used by `CamelCaseStringArray<>`.
16
17@see CamelCaseStringArray
18*/
19type 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/**
29Starts fusing the output of `Split<>`, an array literal of strings, into a camel-cased string literal.
30
31It's separate from `InnerCamelCaseStringArray<>` to keep a clean API outwards to the rest of the code.
32
33@see Split
34*/
35type CamelCaseStringArray<Parts extends string[]> =
36 Parts extends [`${infer FirstPart}`, ...infer RemainingParts]
37 ? Uncapitalize<`${FirstPart}${InnerCamelCaseStringArray<RemainingParts, FirstPart>}`>
38 : never;
39
40/**
41Convert a string literal to camel-case.
42
43This can be useful when, for example, converting some kebab-cased command-line flags or a snake-cased database result.
44
45@example
46```
47import {CamelCase} from 'type-fest';
48
49// Simple
50
51const someVariable: CamelCase<'foo-bar'> = 'fooBar';
52
53// Advanced
54
55type CamelCasedProps<T> = {
56 [K in keyof T as CamelCase<K>]: T[K]
57};
58
59interface RawOptions {
60 'dry-run': boolean;
61 'full_family_name': string;
62 foo: number;
63}
64
65const dbResult: CamelCasedProps<ModelProps> = {
66 dryRun: true,
67 fullFamilyName: 'bar.js',
68 foo: 123
69};
70```
71*/
72export type CamelCase<K> = K extends string ? CamelCaseStringArray<Split<K, WordSeparators>> : K;
Note: See TracBrowser for help on using the repository browser.