1 | import type {Simplify} from './simplify';
|
2 |
|
3 | type SetFieldTypeOptions = {
|
4 | /**
|
5 | Preserve optional and readonly modifiers for properties being updated.
|
6 |
|
7 | NOTE: Property modifiers will always be preserved for properties that are not being updated.
|
8 |
|
9 | @default true
|
10 | */
|
11 | preservePropertyModifiers?: boolean;
|
12 | };
|
13 |
|
14 | /**
|
15 | Create a type that changes the type of the given keys.
|
16 |
|
17 | Use-cases:
|
18 | - Creating variations of a base model.
|
19 | - Fixing incorrect external types.
|
20 |
|
21 | @see `Merge` if you need to change multiple properties to different types.
|
22 |
|
23 | @example
|
24 | ```
|
25 | import type {SetFieldType} from 'type-fest';
|
26 |
|
27 | type MyModel = {
|
28 | readonly id: number;
|
29 | readonly createdAt: Date;
|
30 | updatedAt?: Date;
|
31 | };
|
32 |
|
33 | type MyModelApi = SetFieldType<MyModel, 'createdAt' | 'updatedAt', string>;
|
34 | // {
|
35 | // readonly id: number;
|
36 | // readonly createdAt: string;
|
37 | // updatedAt?: string;
|
38 | // }
|
39 |
|
40 | // `preservePropertyModifiers` option can be set to `false` if you want to remove property modifiers for properties being updated
|
41 | type MyModelApi = SetFieldType<MyModel, 'createdAt' | 'updatedAt', string, {preservePropertyModifiers: false}>;
|
42 | // {
|
43 | // readonly id: number;
|
44 | // createdAt: string; // no longer readonly
|
45 | // updatedAt: string; // no longer optional
|
46 | // }
|
47 | ```
|
48 |
|
49 | @category Object
|
50 | */
|
51 | export type SetFieldType<BaseType, Keys extends keyof BaseType, NewType, Options extends SetFieldTypeOptions = {preservePropertyModifiers: true}> =
|
52 | Simplify<{
|
53 | [P in keyof BaseType]: P extends Keys ? NewType : BaseType[P];
|
54 | } & (
|
55 | // `Record` is used to remove property modifiers
|
56 | Options['preservePropertyModifiers'] extends false ? Record<Keys, NewType> : unknown
|
57 | )>;
|