UNPKG

2.29 kBTypeScriptView Raw
1import type {CamelCase, CamelCaseOptions} from './camel-case';
2import type {NonRecursiveType} from './internal';
3import type {UnknownArray} from './unknown-array';
4
5/**
6Convert object properties to camel case recursively.
7
8This can be useful when, for example, converting some API types from a different style.
9
10@see CamelCasedProperties
11@see CamelCase
12
13@example
14```
15import type {CamelCasedPropertiesDeep} from 'type-fest';
16
17interface User {
18 UserId: number;
19 UserName: string;
20}
21
22interface UserWithFriends {
23 UserInfo: User;
24 UserFriends: User[];
25}
26
27const result: CamelCasedPropertiesDeep<UserWithFriends> = {
28 userInfo: {
29 userId: 1,
30 userName: 'Tom',
31 },
32 userFriends: [
33 {
34 userId: 2,
35 userName: 'Jerry',
36 },
37 {
38 userId: 3,
39 userName: 'Spike',
40 },
41 ],
42};
43```
44
45@category Change case
46@category Template literal
47@category Object
48*/
49export type CamelCasedPropertiesDeep<
50 Value,
51 Options extends CamelCaseOptions = {preserveConsecutiveUppercase: true},
52> = Value extends NonRecursiveType
53 ? Value
54 : Value extends UnknownArray
55 ? CamelCasedPropertiesArrayDeep<Value>
56 : Value extends Set<infer U>
57 ? Set<CamelCasedPropertiesDeep<U, Options>>
58 : {
59 [K in keyof Value as CamelCase<K, Options>]: CamelCasedPropertiesDeep<
60 Value[K],
61 Options
62 >;
63 };
64
65// This is a copy of DelimiterCasedPropertiesArrayDeep (see: delimiter-cased-properties-deep.d.ts).
66// These types should be kept in sync.
67type CamelCasedPropertiesArrayDeep<Value extends UnknownArray> =
68 Value extends []
69 ? []
70 : // Tailing spread array
71 Value extends [infer U, ...infer V]
72 ? [CamelCasedPropertiesDeep<U>, ...CamelCasedPropertiesDeep<V>]
73 : Value extends readonly [infer U, ...infer V]
74 ? readonly [CamelCasedPropertiesDeep<U>, ...CamelCasedPropertiesDeep<V>]
75 : // Leading spread array
76 Value extends readonly [...infer U, infer V]
77 ? [...CamelCasedPropertiesDeep<U>, CamelCasedPropertiesDeep<V>]
78 : Value extends readonly [...infer U, infer V]
79 ? readonly [
80 ...CamelCasedPropertiesDeep<U>,
81 CamelCasedPropertiesDeep<V>,
82 ]
83 : // Array
84 Value extends Array<infer U>
85 ? Array<CamelCasedPropertiesDeep<U>>
86 : Value extends ReadonlyArray<infer U>
87 ? ReadonlyArray<CamelCasedPropertiesDeep<U>>
88 : never;