UNPKG

1.2 kBTypeScriptView Raw
1import type {Except} from './except';
2import type {HomomorphicPick} from './internal';
3import type {KeysOfUnion} from './keys-of-union';
4import type {Simplify} from './simplify';
5
6/**
7Create a type that makes the given keys readonly. The remaining keys are kept as is.
8
9Use-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```
13import type {SetReadonly} from 'type-fest';
14
15type Foo = {
16 a: number;
17 readonly b: string;
18 c: boolean;
19}
20
21type 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*/
31export 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;