1 | import type {Except} from './except';
|
2 | import type {HomomorphicPick} from './internal';
|
3 | import type {KeysOfUnion} from './keys-of-union';
|
4 | import type {Simplify} from './simplify';
|
5 |
|
6 | /**
|
7 | Create a type that makes the given keys readonly. The remaining keys are kept as is.
|
8 |
|
9 | Use-case: You want to define a single model where the only thing that changes is whether or not some of the keys are readonly.
|
10 |
|
11 | @example
|
12 | ```
|
13 | import type {SetReadonly} from 'type-fest';
|
14 |
|
15 | type Foo = {
|
16 | a: number;
|
17 | readonly b: string;
|
18 | c: boolean;
|
19 | }
|
20 |
|
21 | type SomeReadonly = SetReadonly<Foo, 'b' | 'c'>;
|
22 | // type SomeReadonly = {
|
23 | // a: number;
|
24 | // readonly b: string; // Was already readonly and still is.
|
25 | // readonly c: boolean; // Is now readonly.
|
26 | // }
|
27 | ```
|
28 |
|
29 | @category Object
|
30 | */
|
31 | export type SetReadonly<BaseType, Keys extends keyof BaseType> =
|
32 | // `extends unknown` is always going to be the case and is used to convert any
|
33 | // union into a [distributive conditional
|
34 | // type](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#distributive-conditional-types).
|
35 | BaseType extends unknown
|
36 | ? Simplify<
|
37 | Except<BaseType, Keys> &
|
38 | Readonly<HomomorphicPick<BaseType, Keys & KeysOfUnion<BaseType>>>
|
39 | >
|
40 | : never;
|