1 | /**
|
2 | Create a deep version of another object type where property values are recursively replaced into a given value type.
|
3 |
|
4 | Use-cases:
|
5 | - Form validation: Define how each field should be validated.
|
6 | - Form settings: Define configuration for input fields.
|
7 | - Parsing: Define types that specify special behavior for specific fields.
|
8 |
|
9 | @example
|
10 | ```
|
11 | import type {Schema} from 'type-fest';
|
12 |
|
13 | interface User {
|
14 | id: string;
|
15 | name: {
|
16 | firstname: string;
|
17 | lastname: string;
|
18 | };
|
19 | created: Date;
|
20 | active: boolean;
|
21 | passwordHash: string;
|
22 | }
|
23 |
|
24 | type UserMask = Schema<User, 'mask' | 'hide' | 'show'>;
|
25 |
|
26 | const userMaskSettings: UserMask = {
|
27 | id: 'show',
|
28 | name: {
|
29 | firstname: 'show',
|
30 | lastname: 'mask',
|
31 | },
|
32 | created: 'show',
|
33 | active: 'show',
|
34 | passwordHash: 'hide',
|
35 | }
|
36 | ```
|
37 |
|
38 | @category Object
|
39 | */
|
40 | export type Schema<ObjectType, ValueType> = ObjectType extends string
|
41 | ? ValueType
|
42 | : ObjectType extends Map<unknown, unknown>
|
43 | ? ValueType
|
44 | : ObjectType extends Set<unknown>
|
45 | ? ValueType
|
46 | : ObjectType extends ReadonlyMap<unknown, unknown>
|
47 | ? ValueType
|
48 | : ObjectType extends ReadonlySet<unknown>
|
49 | ? ValueType
|
50 | : ObjectType extends Array<infer U>
|
51 | ? Array<Schema<U, ValueType>>
|
52 | : ObjectType extends (...arguments_: unknown[]) => unknown
|
53 | ? ValueType
|
54 | : ObjectType extends Date
|
55 | ? ValueType
|
56 | : ObjectType extends Function
|
57 | ? ValueType
|
58 | : ObjectType extends RegExp
|
59 | ? ValueType
|
60 | : ObjectType extends object
|
61 | ? SchemaObject<ObjectType, ValueType>
|
62 | : ValueType;
|
63 |
|
64 | /**
|
65 | Same as `Schema`, but accepts only `object`s as inputs. Internal helper for `Schema`.
|
66 | */
|
67 | type SchemaObject<ObjectType extends object, K> = {
|
68 | [KeyType in keyof ObjectType]: ObjectType[KeyType] extends readonly unknown[] | unknown[]
|
69 | ? Schema<ObjectType[KeyType], K>
|
70 | : Schema<ObjectType[KeyType], K> | K;
|
71 | };
|