6737a3dc63e59086d35c61ae74921c82f5a2efdd12de297f6b16ac64915eb147c3129666b56ba9ffbb0eeaa5c6e7b8dfb23450c25ad73c65a743b497269faa 1.8 KB

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